我知道stringstream
可以使用stringstream::str()
进行更新,但是如果在此之后向stringstream
输入了其他内容,则不会按预期工作。下面的代码演示的现象:使用stringstream更新后,C++ stringstream无法正常工作:str()
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream ss; //ostringstream gives the same output
ss << "Original string ";
ss.str("Updated string ");
ss << "sth else";
cout << ss.str() << endl;
}
我希望得到的输出
Updated string sth else
但它实际上输出
sth elsestring
看来,宁可追加在最近输入的字符串当前字符串的结尾(在我的例子中为Updated string
),它试图从头开始覆盖它。我的代码有什么问题?
当使用stringstream时,你必须处理输入/输出位置和状态 - 避免它,并使用istingstream或ostingstream。 – 2015-02-10 23:20:54
@DieterLücking感谢您的建议。我试过ostringstream,它给出了相同的输出。 – 2015-02-10 23:26:48
另外,不要重复使用它 - 使用一个新的实例,而不是用str来操作缓冲区(....) – 2015-02-10 23:29:17