【问题标题】:strlen() not working with string variablestrlen() 不适用于字符串变量
【发布时间】: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*)'
  • 无论你从什么来源学习,扔掉它,得到一本像样的书。

标签: c++ c++11 strlen


【解决方案1】:

strlen 是来自 C 的函数,适用于 C 字符串 (char *)。

对于正确的 C++ std::strings,请使用 .length() or .size() 成员函数。

事实上,大多数以“c”开头的标准头文件都包含 C++ 从 C 继承的函数。在您的情况下,如果您已经在使用 C++ 字符串,您很可能没有任何理由使用 &lt;cstring&gt;

【讨论】:

    【解决方案2】:

    只要你改变了,你的情况就会奏效

    string b="hello";
    

    char* b = "hello";
    

    请注意,C 字符串总是(应该)有空字符 '\0' 来确定字符串的结尾。 简单解释一下,例如here

    【讨论】:

    • 你肯定是说,C 字符串必须以'\0' 结尾,而不是'\n'
    • @cwschmidt 啊哈,你说得对:D 我可能应该睡一会
    • 还有const char *b 而不是char *b
    • @cwschmidt 很好,在示例中字符串不是 const
    • @Peregrin 你指的是什么?是不是const无关紧要,C字符串必须以'\0'结束
    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多