C++:为什么重新输入字符串流不起作用?内容保持不变 [英] C++: Why re-input stringstream doesn't work? the content remains the same

查看:39
本文介绍了C++:为什么重新输入字符串流不起作用?内容保持不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 C++ 中 stringstream 的详细信息.但是当我尝试重新输入 ("<<") stringstream 对象时,我发现了一个问题.(即 obj 的内容仍然保持不变.)我的代码如下.输出显示在注释中.

I am trying to understand the details of the stringstream in C++. But I find a trouble when I tried to re-input ("<<") the stringstream object. (i.e. the content of the obj still remains the same.) My code is as follows. Outputs are shown in comments.

#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;
}

为什么?我不明白---problem here---"的结果.为什么 sso 不接受新输入?

Why? I don't understand the result in "---problem here---". Why doesn't the sso accept new inputs?

赞赏,

推荐答案

sso >> 最后一次阅读r1>>r2>>r3; 将流置于失败状态,因为当它仍在尝试为 r3 读取更多字符时,没有更多可用字符.

The last read of sso >> r1 >> r2 >> r3; puts the stream into fail state because no more characters were available while it was still trying to read more characters for r3.

在失败状态下,流不能被写入或读取.要解决您的问题,将 sso.clear(); 移至 sso <<<;D".

In fail state the stream cannot be written to or read from. To fix your problem move sso.clear(); up to before sso << "D".

如果在 C 之后输出一个额外的空格,你会看到不同的行为,因为这样流不会进入失败状态(它成功读取 r3 而仍然有空格在流中).

You can see different behaviour if you output an extra space after C because then the stream does not enter fail state (it successfully reads r3 while there is still the space in the stream).

这篇关于C++:为什么重新输入字符串流不起作用?内容保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆