strlen()无法与字符串变量一起使用 [英] strlen() not working with string variable
本文介绍了strlen()无法与字符串变量一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string b="hello";
cout<<b;
int c = strlen(b);
cout << "Hello world!" <<c<< endl;
return 0;
}
当我尝试运行此命令时,出现以下错误
When I try to run this I get the error below
||=== Build: Debug in strlen (compiler: GNU GCC Compiler) ===|
C:\Users\Waters\Desktop\hellow world\strlen\main.cpp||In function 'int main()':|
C:\Users\Waters\Desktop\hellow world\strlen\main.cpp|14|error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'size_t strlen(const char*)'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
推荐答案
strlen
是C语言的函数,可用于C字符串( char *
)。
对于正确的C ++ std :: string
s,请使用< a href = http://en.cppreference.com/w/cpp/string/basic_string/size> .length()
或。 size()
成员函数。
For proper C++ std::string
s use the .length()
or .size()
member functions.
事实上,大多数以'c'开头的标准标头都包含C ++从C继承的函数如果您已经在使用C ++字符串,就很可能没有理由使用< cstring>
。
In fact most standard headers that start with 'c' include functions that C++ inherited from C. In your case you most likely don't have any reason to use <cstring>
if you're already working with C++ strings.
这篇关于strlen()无法与字符串变量一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文