|
-
August 3rd, 2012, 07:50 AM
#1
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!!
-
August 3rd, 2012, 08:04 AM
#2
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
-
August 3rd, 2012, 08:06 AM
#3
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.
Last edited by aseminov; August 3rd, 2012 at 08:10 AM.
-
August 3rd, 2012, 08:34 AM
#4
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
-
August 3rd, 2012, 12:42 PM
#5
Re: ifstream not reading next line?
 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
-
August 3rd, 2012, 02:44 PM
#6
Re: ifstream not reading next line?
 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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|