0

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?

Razib
  • 10,965
  • 11
  • 53
  • 80
Atul Kumar Verma
  • 369
  • 3
  • 8
  • 23
  • 1
    The usual error not testing the extraction, use: `while(line_stream >> temp) cout << temp<< " ";` –  Feb 01 '15 at 17:06
  • The same problematic pattern is analyzed very well here: http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong . It covers C++ as well. – AnT stands with Russia Feb 01 '15 at 17:30

1 Answers1

1

Because of this:

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

which fails for the same reason that while (!line_stream.eof()) would fail.

When you have read the last integer, you haven't reached the end of the stream yet - that will happen on the next read.

And the next read is the unchecked line_stream >> temp;, which will fail and leave temp untouched.

The proper form for such a loop is

while (line_stream >> temp)
{
    cout << temp<< " ";
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82