首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >stringstream的奇怪行为?

stringstream的奇怪行为?
EN

Stack Overflow用户
提问于 2016-05-05 19:18:32
回答 2查看 71关注 0票数 0

我不能理解为什么在到达最后一个单词后,它不输出空白或空字符或垃圾值或其他任何东西。为什么>>在结束字符串后没有任何影响。

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
    stringstream ss("I am going to goa for");  // Used for breaking words
    string word; // To store individual words
    while (ss >> word)
        cout<<word<<"\n";
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
}

输出:

代码语言:javascript
复制
I
am
going
to
goa
for
for
for
for
EN

回答 2

Stack Overflow用户

发布于 2016-05-05 21:34:24

>>到达字符串末尾时,将设置故障位,并停止进一步读取。

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
    stringstream ss("I am going to goa for");  // Used for breaking words
    string word; // To store individual words
    while (ss >> word)
        cout<<word<<"\n";

    word = "END";
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
}

您看到的是for,因为它是存储在其中的内容。将其更改为其他值,您会发现在清除failbit之前,它不会从stringstream中读取。

输出为:

代码语言:javascript
复制
I
am
going
to
goa
for
END
END
END

有关更多详细信息,请参阅stringstream

票数 1
EN

Stack Overflow用户

发布于 2016-05-05 21:32:07

在每个cout << word << endl;行之前,您应该添加if(!ss.fail()),以检查在读取尝试之后,字符串流中是否没有发生错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37049243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档