在这个最小的例子中,字符串流的输入和以前使用的 cout 的内容之间有一个奇怪的混乱:
在线gdb: https ://onlinegdb.com/itO69QGAE
代码:
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
const char sepa[] = {':', ' '};
const char crlf[] = {'\r', '\n'};
int main()
{
cout<<"Hello World" << endl;
stringstream s;
string test1 = "test_01";
string test2 = "test_02";
s << test1;
cout << s.str() << endl;
// works as expected
// excpecting: "test_01"
// output: "test_01"
s << sepa;
cout << s.str() << endl;
// messing up with previous cout output
// expecting: "test_01: "
// output: "test_01: \nHello World"
s << test2;
cout << s.str() << endl;
// s seems to be polluted
// expecting: "test_01: test_02"
// output: "test_01: \nHello Worldtest_02"
s << crlf;
cout << s.str() << endl;
// once again messing up with the cout content
// expecting: "test_01: test_02\r\n"
// output: "test_01: Hello Worldtest_02\r\nHello World"
return 0;
}
所以我想知道为什么会这样?
因为它仅在将 char 数组推入 stringstream 时才会发生,这很可能是这样的......但根据参考,stringstream 的“<<”-operator 可以/应该处理 char*(这个数组的名称实际上代表什么) .
除此之外,stringstream 和 cout 之间似乎存在(?隐藏的,或者至少不明显的?)关系。那么为什么内容会污染到字符串流中呢?
在这个例子中是否有任何错误/愚蠢的用法或者狗被埋在哪里(-> 德语成语 :P )?
最好的问候和感谢达米安
PS我的问题不是关于“解决”这个问题,比如使用字符串而不是char数组(这会起作用)......这是关于理解内部机制以及为什么这实际上会发生,因为对我来说这只是一个意想不到的行为.