问题
While reading this question, I found in the answers different way of reading an integer. Here are two of them.
The one from πάντα ῥεῖ's answer:
if(iFile) {
iFile >> int1;
cout << "From first file:" << int1 << endl;
}
The one from JRowan's answer:
if(!iFile.eof()){
iFile >> int1;
cout << "From first file:" << int1 << endl;
}
But I was wondering if using the code below is equivalent to the two above? Also, is there any reason not to use one of the three sample codes?
if (iFile >> int1) {
cout << "From first file:" << int1 << endl;
}
Thanks.
回答1:
On constructing the ifstream
object iFile
, you should check that there were no errors. This is correctly accomplished by simply doing if(iFile)
in both C++ and C++11. Assuming you have already done this check, the third code snippet is the only correct way of reading the ints from file. The first two methods will end up printing the last integer before eof
twice. This is because they don't check the state of the stream after doing iFile>>int1
. So, if they had encountered eof, you wouldn't know and continue to call cout
.
回答2:
The third code is "less protected". It tries to read and if it can, it outputs the result. Meanwhile, the first one verifies if the reference to the file isn't null before trying to read and the second one verify if it has some data or it is just EOF.
The better option for you to use in case you want to read a file completely is to:
if(iFile){
while(!iFile.eof()){
iFile >> int1;
cout << "Number read: " << int1 << endl;
}
}
Excluding those cases that is just a matter of how you want to write your code.
来源:https://stackoverflow.com/questions/25955218/on-comparing-different-way-of-reading-an-integer-from-a-file