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.
}
2
  • @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...
    – Nim
    Oct 14, 2013 at 14:00
  • 1
    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. Oct 15, 2013 at 11:18
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
  • 13
    Just plain wrong. (Anytime you see istream::eof() as a loop condition, the code is almost certainly wrong.) Apr 7, 2011 at 11:04
  • 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.) Apr 7, 2011 at 13:43
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

-5

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

while(!inFile.eof())
{
    inFile >> data;
    if ( data < 0 ) {
      break;
    }
}
1
  • 5
    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). Jan 4, 2012 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.