3

Im trying to write a simple code in c++ to read in integer from a text file, the code should stop reading when it encounter a negative integer. The txt file contains 1 positive integer on each line, and the last line is a negative integer.

My code right now using eof, and it reads in negative integer also, which I dont want.

while(!inFile.eof()) { inFile >> data; } 

Text file

10 22 33 34 -1 

Thanks in advance :)

4 Answers 4

9

hmm..

int data = 0; while(inFile >> data && data >= 0) { // do stuff with data. } 
Sign up to request clarification or add additional context in comments.

2 Comments

@LightnessRacesinOrbit, I thought the code pretty succinctly explained what needed to be done... a curious reader ought to be able to take what is there and investigate bits they are not sure of - a valuable skill IMO...
Yes, I agree, but when the OP has already indicated that he is missing some understanding in this area, changing bits of code without explaining why you did that is often more harmful than not. Otherwise he may think that you got rid of while (!eof) only for style reasons, for example.
4

You would at least need to read the negative number to determine that you have reached end of input.

while( inFile >> data) { if ( data < 0 ) break; } 

2 Comments

Just plain wrong. (Anytime you see istream::eof() as a loop condition, the code is almost certainly wrong.)
But not the comment:-). Using istream::eof() was an error in the original code, and this should be pointed out. (Otherwise, Nim's answer is perfect.)
1
while(!infile.eof()) { infile>>data; if(data>0) cout<<data; } 

read from the file check if it is greater than zero then print it

Comments

-5

Maybe something like this, which tries to test the incoming integer, would work:

while(!inFile.eof()) { inFile >> data; if ( data < 0 ) { break; } } 

1 Comment

Because the answer is wrong: The EOF is not hit until you try and read past the EOF. So EOF is not set before inFile >> data; but will be set after this call. When it is set you still use data even though the valu is now basically random. Rember the last successful read will read up-to but not past the EOF. The last read will attempt to read past and fail (at which point you can't use the value you were reading into).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.