你能给C++11字符串添加null终止符并对它们进行迭代吗



在C++11中,将null终止符放在C++11字符串中,然后在字符串的整个长度上迭代是否合法?

#include <string>
#include <iostream>
int main(int argc, char** argv) {
std::string s("helloworldn");
for (char c : s) {
std::cout << " " << (unsigned int)c;
}
std::cout << std::endl;
return 0;
}

是的,你可以,但你需要告诉构造函数你要传递多少个字符。否则,构造函数将尝试通过搜索null终止符来确定长度(即strlen的方法(,结果会得到错误的答案。

std::string s("helloworldn", 14);

演示

最新更新