strlen() not working with string variable

柔情痞子 提交于 2019-12-11 05:46:42

问题


#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)) ===|

回答1:


strlen is a function from C and works with C strings (char *).

For proper C++ std::strings use the .length() or .size() member functions.

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.




回答2:


your case will work if you just changed

string b="hello";

to

char* b = "hello";

note that C strings always (should) have null character '\0' that determines that end of the string. It's explained briefly for example here



来源:https://stackoverflow.com/questions/37494307/strlen-not-working-with-string-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!