输出的时候为什么word会输出两次?

将一串字符串以空格进行分割,并将字符串到着输出,但是字符串的最后面存在空格,例如“hello word ”,输出的时候为什么word会输出两次??

#include<iostream>
#include<string>
#include<stack>
#include<sstream>
using namespace std;
int main() {
    string s;
    getline(cin,s);
    istringstream str(s);
    string ret = "", s1;
    stack<string>sta;
    while (!str.eof())
    {
        str >> s1;
        cout << s1 << endl;
        sta.push(s1);
    }
    while (!sta.empty())
    {
        ret += sta.top() + ' ';
        sta.pop();
    }
    if (ret.size() != 0)ret.pop_back();
    system("pause");
    return 0;

}

因为istringstream 是按空格区分的,最后有一个空格的话,循环判断istringstream没有到最后,它会再读取一次,而最后只有一个空格,返回值没有得到更新,就会返回上一个结果。

你可以再while循环中加几个str>>a,输出以下看看。
就算最后不是空格,str>>s1 这个命令一样可以多次执行,只是值得不到更新。