【发布时间】:2021-07-27 08:55:28
【问题描述】:
在这个最小的例子中,字符串流的输入和以前使用的 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 和 cout 之间似乎存在(?隐藏的,或者至少不明显的?)关系。那么为什么内容会污染到字符串流中呢?
在这个例子中是否有任何错误/愚蠢的用法或者狗被埋在哪里(-> 德语成语 :P )?
最好的问候和感谢 达米安
附:我的问题不是关于“解决”这个问题,比如使用字符串而不是 char 数组(这将起作用)......它是关于理解内部机制以及为什么这实际上会发生,因为对我来说这只是一个意想不到的行为。
【问题讨论】:
-
对于
s << sepa;,您将sepa视为以空字符结尾的字符串。它不是,所以你有未定义的行为。与s << crlf;相同。为什么不制作sepa和crlf实际字符串?或者甚至使用s << ": ";和s << "\r\n";中的文字字符串? -
@Someprogrammerdude 给出了答案 - 还包括这种未定义行为的实际效果
标签: c++ cout stringstream