我有这个函数,编译器对我大喊“无法将字符串转换为 const char”。
void
DramaticLetters(string s, short TimeLength)
{
for(int i = 0, sLen = strlen(s); i < sLen; i++){
cout << s[i];
Sleep(TimeLength);
}
}
我认为strlen有问题
strlen()
用于 Cconst char*
字符串。要获取字符串的长度s
,请使用s.size()
或s.length()
。如果要从 a 中获取 C 字符串string
,请使用s.c_str()
.
尽管 C++ 使它看起来可以互换,但在const char*
转换为.string
const char*
string
您没有理由要使用strlen
其中任何一个。strlen
最有可能用循环定义,它永远不会像 一样有效size()
,这很可能只是string
类的长度属性的吸气剂。只有string
在调用没有 C++ 替代方案的 C 函数时才转换为 C 字符串。
您不应混合使用 C 和 C++ 字符串函数。而不是strlen()
(一个C风格的函数),使用string::size()
:
for(int i = 0, sLen = s.size(); i < sLen; i++) {
cout << s[i];
Sleep(TimeLength);
}
在这里,您可以参考class 中的所有方法string
。
正如克里斯在他的评论中所说, strlen 用于 a const char *
,而您将其传递给 a string
。代替
for(int i = 0, sLen = strlen(s); i < sLen; i++){
cout << s[i];
Sleep(TimeLength);
}
用这个:
for(int i = 0, sLen = s.length(); i < sLen; i++){
cout << s[i];
Sleep(TimeLength);
}
strlen
上运行char const *
。如果你真的想,你可以做strlen(s.c_str())
,但std::string
有很多功能,包括一个length()
方法,它返回字符串中的字符数
几点说明:
您不要修改函数内的字符串,因此最好将 const 引用传递给它(const string& s)
字符串本身定义了获取其长度的方法 - s.size() 和 s.length() 都可以。额外的好处是这两种方法在复杂性方面都是恒定的,而不是 strlen 的线性复杂性
如果您真的想使用 strlen,请使用 s.c_str():strlen(s.c_str())