0

I was trying to read a pair of values line wise from a file but the integers i and j were not updating. Was my assignment of i and j wrong? I've found a way to get the code to work but I'm curious to know why the first while loop did not work.

Console output:

127 86
127 86

141 127
127 86

153 127
127 86

165 127
127 86

171 127
127 86

174 127
127 86

191 27
127 86

191 87
127 86

191 99
127 86

191 102
127 86

MWE:

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

void test()
{
    ifstream inputfile;
    inputfile.open("test.txt");
    string line;
    stringstream lineS;
    int i, j;

    while ( getline( inputfile, line ) )
    {
        lineS.str(line);
        cout << lineS.str() << endl;
        lineS >> i >> j;
        cout << i << " " << j << endl << endl;
    }

    /* This works
    while (!inputfile.eof()) {
        inputfile >> i >> j;
        cout << i << " " << j << endl << endl;
    }*/
    inputfile.close();
}

int main()
{
    test();
    return 0;
}

This is the text file test.txt:

127 86
141 127
153 127
165 127
171 127
174 127
191 27
191 87
191 99
191 102
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BlackAdder
  • 127
  • 8

2 Answers2

0

The problem seems to be that when you have read from lineS once, the eofbit flag is set and it's not cleared when resetting the string. Either that or there is a bug in your standard library code that doesn't reset the reading position properly when you reset the string.

Two solutions: Either clear the stream state manually each loop, or define lineS inside the loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You have not reset the stream's get pointer to the beginning of the string. It does not matter that you have changed the underlying string.

The better idiom is to construct the stringstream inside the loop:

while ( getline( inputfile, line ) )
{
  istringstream lineS( line );
  lineS >> i >> j >> ws;
  if (!lineS.eof()) inputfile.setstate( ios::failbit );
}

Notice also that any input error is recognized and propagated back to the originating input stream.

Hope this helps.

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39