【发布时间】:2016-05-28 01:17:28
【问题描述】:
#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;
}
当我尝试运行它时,我收到以下错误
||=== 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(b.c_str()) -
更好:试试
c = b.length() -
@WatersSharma:因为
strlen接受char *参数,而不是std::string,这对它来说完全没有意义。std::string::c_str()是一个返回 C 字符串 (const char *) 的函数。 -
@WatersSharma:如果您费心阅读错误消息,它会在此处显示:
cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'size_t strlen(const char*)' -
无论你从什么来源学习,扔掉它,得到一本像样的书。