我不能理解为什么在到达最后一个单词后,它不输出空白或空字符或垃圾值或其他任何东西。为什么>>在结束字符串后没有任何影响。
#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;
}输出:
I
am
going
to
goa
for
for
for
for发布于 2016-05-05 21:34:24
当>>到达字符串末尾时,将设置故障位,并停止进一步读取。
#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中读取。
输出为:
I
am
going
to
goa
for
END
END
END有关更多详细信息,请参阅stringstream。
发布于 2016-05-05 21:32:07
在每个cout << word << endl;行之前,您应该添加if(!ss.fail()),以检查在读取尝试之后,字符串流中是否没有发生错误。
https://stackoverflow.com/questions/37049243
复制相似问题