【发布时间】: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 >> temp) cout << temp<< " "; -
同样的问题模式在这里分析得很好:stackoverflow.com/questions/5431941/…。它也涵盖了 C++。
标签: c++ input int stringstream