使用字符串流从 c++ 中的字符串中提取整数时意外重复

Unexpected repetition while extracting integers from string in c++ using stringstream

本文关键字:字符串 整数 意外 提取 c++      更新时间:2023-10-16

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

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) {
    line_stream >> temp;
    cout << temp<< " ";
}

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

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

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

这种循环的正确形式是

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