ifstream not reading next line?
Hello all,
I have a file blah.txt like this:
3 1 4
1 2 3
and here is my code to read in that file:
Code:
int x = 0, y = 0, z = 0;
ifstream data("blah.txt");
while(x != 1)
{
data >> x >> y >> z;
}
For some reason, it just keeps readin in the values: 3 1 4
What am I doing incorrectly?
Thanks!!
Re: ifstream not reading next line?
First of all you should check for a successfu read.
Seems that reading fails and that's why you get an infinite loop.
try something like this
Code:
int x = 0, y = 0, z = 0;
ifstream data("blah.txt");
while( data >> x >> y >> z)
{
if ( x == 1 )
break;
}
Kurt
Re: ifstream not reading next line?
Ok I see what you mean... obviously my "data >> x >> y >> z" is failing. How do I debug why it failed?
Thanks.
Re: ifstream not reading next line?
I'd add some output statements
e.g.
Code:
int x = 0, y = 0, z = 0;
ifstream data("blah.txt");
while( data >> x >> y >> z)
{
std::cout << "x:" << x << " y:" << y << " z:" << z << std::endl;
if ( x == 1 )
break;
}
std::cout << "after loop x:" << x << " y:" << y << " z:" << z << std::endl;
if that doesnt give you any clue then I would check "blah.txt"
Kurt
Re: ifstream not reading next line?
Quote:
Originally Posted by
aseminov
Hello all,
I have a file blah.txt like this:
3 1 4
1 2 3
and here is my code to read in that file:
Code:
int x = 0, y = 0, z = 0;
ifstream data("blah.txt");
while(x != 1)
{
data >> x >> y >> z;
}
For some reason, it just keeps readin in the values: 3 1 4
What am I doing incorrectly?
Thanks!!
It is the way streams operate. You never read the EOL.
Try adding this to your code:
Code:
data >> x >> y >> z; // Read the values from the file for each line
data.ignore(512, '\n'); // skip past the EOL
Re: ifstream not reading next line?
Quote:
Originally Posted by
cconn64
It is the way streams operate. You never read the EOL.
Not true. '\n' is whitspace and the streamextractor for an int skips leading whitspaces by default.
Kurt