C ++:为什么重新输入stringstream不起作用?内容保持不变

时间:2017-01-13 04:36:48

标签: stream stringstream

我试图理解C ++中stringstream的细节。但是当我尝试重新输入(“<<”)stringstream对象时,我发现了一个麻烦。 (即obj的内容仍然保持不变。)我的代码如下。输出显示在注释中。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    stringstream sso;
    cout <<"orginal: " << sso.str() <<endl; //orginal:"empty"
    sso << "A" << " " << "B" << " " << "C";
    cout <<"flowin:" << sso.str() <<endl; //flowin:A B C

    string r1, r2, r3;
    sso >> r1 >> r2 >> r3;
    cout << "flowout:" << r1 << r2 << r3 << endl;//flowout:ABC
    cout << "base: " << sso.str() << endl; //base: A B C

    cout << "----problem here-----" << endl;
    sso << "D" << " " << "E" << " " << "F";
    cout <<"flowin:" << sso.str() <<endl; //flowin:A B C

    cout << "----this works-----" << endl;
    sso.clear(); //clear flag
    sso.str(""); //clear content
    sso << "D" << " " << "E" << " " << "F";
    cout <<"flowin:" << sso.str() <<endl; //flowin:D E F

    return 0;
}

为什么呢?我不明白“---问题---”的结果。为什么sso不接受新的输入?

Apprecited,

1 个答案:

答案 0 :(得分:1)

最后一次读取r3会将流置于失败状态,因为当它仍在尝试为sso.clear();读取更多字符时,没有其他字符可用。

在失败状态下,无法写入或读取流。要解决您的问题,请将sso << "D"移至C之前。

如果在r3之后输出额外的空格,则可以看到不同的行为,因为流不会进入失败状态(它在流中仍有空间时成功读取 In LOOP till file ends read file Read every line as string Use .split() method to seperate them as individual token Store name in String array and Other one in Integer array LOOP close )。