我写了一个简短的测试程序,看看我是否可以重复使用 stringstream 附加到一个字符串。
在第一个版本中,我得到了 Output1,但我真的不明白为什么 s1 保持为空。我发现我必须做 ss.clear() 然后在 Output2 中得到预期的结果。任何人都可以解释为什么它在没有明确的情况下不起作用?我本以为,如果我反复输入数字并将它们取回字符串,我应该总是得到数字。我不确定是否附加了数字,但这与此示例无关。
这里:http ://www.cplusplus.com/reference/sstream/stringstream/它说我可以使用任何操作,并且没有限制或要求重置字符串,我可以看到。我也不明白为什么之后我在没有 ss.clear() 的情况下得到输出。
我也有点惊讶 s0 之后保持不变。因此,如果流已经有内容,它不会覆盖或重置字符串吗?
我在 cygwin 中使用 gcc 3.4.4。
int main()
{
std::string s0;
std::string s1;
int n = 1;
std::stringstream ss;
ss << n;
ss >> s0;
cout << "S0:" << s0 << endl;
ss.clear(); <-- If I remove this, then s1 stays empty.
n = 2;
ss << n;
ss >> s1;
cout << "S1:" << s1 << endl;
ss << n;
ss >> s0;
cout << "S0_2:" << s0 << endl; <-- Why is s0 still 1?
}
输出1:
S0:1
S1:
S0_2:1
输出2:
S0:1
S1:2
S0_2:1