
c++中的strlen怎么调用?
我写了一个求字符串的长度的代码,用c语言编得行,可是用c++却不得行,不知是什么原因?高手帮忙。c语言:include<stdio.h>include<string.h>...
我写了一个求字符串的长度的代码,用c语言编得行,可是用c++却不得行,不知是什么原因?高手帮忙。
c语言:
include<stdio.h>
include<string.h>
void main()
{ char *a;
int b;
scanf("%s",a);
b=strlen(a);
printf("%d",b);
}
c++:
include<iostream.h>
include<string.h>
void main()
{
string a;
int b;
cin>>a;
b=strlen(a);
cout<<b;
}
c++始终提示(这几段英文没看懂):
c:\whoyousee\2\2.cpp(10) : error C2664: 'strlen' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 展开
c语言:
include<stdio.h>
include<string.h>
void main()
{ char *a;
int b;
scanf("%s",a);
b=strlen(a);
printf("%d",b);
}
c++:
include<iostream.h>
include<string.h>
void main()
{
string a;
int b;
cin>>a;
b=strlen(a);
cout<<b;
}
c++始终提示(这几段英文没看懂):
c:\whoyousee\2\2.cpp(10) : error C2664: 'strlen' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 展开
3个回答
展开全部
string a;
这样是不对的
应该定义成char a[100];
另外,其实你的C版也是错的,因为你没给输入分配空间,正确的定义方法还是上面那样,或者加上一句
s = (char*)malloc(100);
这样是不对的
应该定义成char a[100];
另外,其实你的C版也是错的,因为你没给输入分配空间,正确的定义方法还是上面那样,或者加上一句
s = (char*)malloc(100);
展开全部
string 是个对象, 取它的长度可以用它的方法的: int b = a.size();
这是正道;
如果你就想用 strlen 地话, 应该这样: int b = strlen(a.c_str());
使用成员 c_str() 将 C++ 的字符串 a 转换成 C 的字符串;
这是正道;
如果你就想用 strlen 地话, 应该这样: int b = strlen(a.c_str());
使用成员 c_str() 将 C++ 的字符串 a 转换成 C 的字符串;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
因为C++里没有string.h这个头文件,今天才听老师讲了。你用的是旧式的#include<iostream.h>
#include<string.h>
如果用下面的新式的就行
#include<iostream>
#include<string>
using namespace std;
因为using namespace std可以把C的string.h也包含进去,这就是新旧的差别!
#include<string.h>
如果用下面的新式的就行
#include<iostream>
#include<string>
using namespace std;
因为using namespace std可以把C的string.h也包含进去,这就是新旧的差别!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询