开发者

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 fi开发者_JAVA技巧le

10
22
33
34
-1   

Thanks in advance :)


hmm..

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


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;
}


while(!infile.eof())
{
infile>>data;
if(data>0)
cout<<data;
}

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜