【问题标题】:Unexpected repetition while extracting integers from string in c++ using stringstream使用stringstream从c ++中的字符串中提取整数时出现意外重复
【发布时间】:2015-03-31 15:54:30
【问题描述】:

我正在尝试读取一个文件,该文件由由空格分隔的整数组成的行组成。我想将每一行存储为一个单独的整数向量。 所以我尝试逐行读取输入并使用

从中提取整数
stringstream

我用来提取的代码如下-

#include <bits/stdc++.h>
using namespace std;

int main()
{
    freopen("input.txt","r",stdin);
    string line;
    while(getline(cin, line)) {
    int temp;
    stringstream line_stream(line); // conversion of string to integer.
    while(line_stream) {
        line_stream >> temp;
        cout << temp<< " ";
    }
    cout << endl;
   }
   return 0;
}

上面的代码有效,但它重复了最后一个元素。例如,输入文件-

1 2 34
5 66

输出:

1 2 34 34
5 66 66

我该如何解决这个问题?

【问题讨论】:

  • 不测试提取的常见错误,使用:while(line_stream &gt;&gt; temp) cout &lt;&lt; temp&lt;&lt; " ";
  • 同样的问题模式在这里分析得很好:stackoverflow.com/questions/5431941/…。它也涵盖了 C++。

标签: c++ input int stringstream


【解决方案1】:

因为这个:

while(line_stream) {
    line_stream >> temp;
    cout << temp<< " ";
}

失败的原因与while (!line_stream.eof()) 失败的原因相同。

当您读取最后一个整数时,您还没有到达流的末尾 - 这将在下一次读取时发生。

下一次读取是未选中的line_stream &gt;&gt; temp;,它将失败并保持temp 不变。

这种循环的正确形式是

while (line_stream >> temp)
{
    cout << temp<< " ";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2015-11-30
    • 2021-05-19
    • 2020-05-04
    相关资源
    最近更新 更多