I am trying to read a file which consist of lines that are made of space separated integers. I want to store each line as a separate vector of integers. so I tried reading input line by line and extracting integers from it using
stringstream
The code I have used for extraction is as follows -
#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;
}
Above code works but it repeats the last element.For example, input file -
1 2 34
5 66
output:
1 2 34 34
5 66 66
How can I fix this?