请问这里的s1和s2为什么是不一样的字符串呀?

string s1 = "\0w#234";
string s2 = "aw#234";
s2[0] = '\0';
cout << s1<<  endl;
cout << s2 << endl;

image.png
s1打印出来是空串,s2打印出来就不是

阅读 2.2k
2 个回答

补充一下 Ethson 的答案:

string s1 = "\0w#234"; 使用一个字符指针初始化一个 std::string 。字符指针没有长度信息,构造时是按 0 结尾处理的。所以 s1 的内容就是一个空串(长度是 0 )。

#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 的重载并不是你认为的简单的字符串的输出,而是把这个 stringsize() 个字符输出来,所以不会出现遇到 \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())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题