2

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 :)

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
Kyle Mai
  • 113
  • 2
  • 13

4 Answers4

8

hmm..

int data = 0;
while(inFile >> data && data >= 0) 
{
 // do stuff with data.
}
Nim
  • 32,149
  • 2
  • 56
  • 98
  • @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 '13 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. – Lightness Races in Orbit Oct 15 '13 at 11:18
3

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;
}
Shamim Hafiz
  • 19,616
  • 36
  • 104
  • 164
  • 13
    Just plain wrong. (Anytime you see `istream::eof()` as a loop condition, the code is almost certainly wrong.) – James Kanze Apr 07 '11 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.) – James Kanze Apr 07 '11 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;
    }
}
Pete Wilson
  • 8,198
  • 6
  • 33
  • 50
  • 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). – Martin York Jan 04 '12 at 01:08