string s1 = "\0w#234";
string s2 = "aw#234";
s2[0] = '\0';
cout << s1<< endl;
cout << s2 << endl;
s1打印出来是空串,s2打印出来就不是
string s1 = "\0w#234";
string s2 = "aw#234";
s2[0] = '\0';
cout << s1<< endl;
cout << s2 << endl;
s1打印出来是空串,s2打印出来就不是
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "\0w#234";
string s2 = "aw#234";
s2[0] = '\0';
cout << s1 << endl; // (空)
cout << s1.size() << endl; // 0
cout << s2 << endl; // w#234
cout << s2.c_str() << endl; // (空)
for (int i = 0; i < (int)s2.size(); ++i)
{
cout << s2[i]; // w#234
}
cout << endl;
return 0;
}
因为 operator<<
对 std::string
的重载并不是你认为的简单的字符串的输出,而是把这个 string
的 size()
个字符输出来,所以不会出现遇到 \0
就截断的现象。
参见:https://en.cppreference.com/w...
Then stores each character from the resulting sequence (the contents of str plus padding) to the output stream os as if by calling os.rdbuf()->sputn(seq, n), where n is std::max(os.width(), str.size())
3 回答1.1k 阅读✓ 已解决
1 回答1k 阅读✓ 已解决
4 回答791 阅读
1 回答869 阅读
1 回答899 阅读
1 回答668 阅读
1 回答775 阅读
补充一下 Ethson 的答案:
string s1 = "\0w#234";
使用一个字符指针初始化一个std::string
。字符指针没有长度信息,构造时是按 0 结尾处理的。所以s1
的内容就是一个空串(长度是 0 )。