Saturday, March 2, 2019

c++ - How do you stop reading integer from text file when encounter negative integer?



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


Answer



hmm..




int data = 0;
while(inFile >> data && data >= 0)
{
// do stuff with data.
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...