【问题标题】:about istringstream and >>operator关于 istringstream 和 >> 运算符
【发布时间】:2015-11-25 05:41:05
【问题描述】:
string str = "0.000 0.005 0.001";
istringstream s(str);
string sub;
while (s)
{
    s >> sub;
    cout << sub << endl;
}

这是我的代码,我只想输出str 中的每个数字,但我得到了最后一个数字两次。我知道有很多更好的方法来实现它,但我想知道这段代码有什么问题。我在operator&gt;&gt; 上是否有什么问题?

【问题讨论】:

  • 该代码不会将每个数字输出两次,它只会输出 last 数字两次。

标签: c++ istringstream


【解决方案1】:

使用

while (s >> sub)
{
    cout << sub << endl;
}

相反。在您的代码中,您最终会“吃掉”流的结尾,因此 s &gt;&gt; sub 失败,并且 sub 在最后一次良好读取(即最后一个数字)时保持不变,因此您最终会显示它两次。

相关:Why is iostream::eof inside a loop condition considered wrong?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2014-10-28
    相关资源
    最近更新 更多