#include <iostream>#include<fstream>#defineMAXSIZE 1000using namespacestd;intMain () {intA[maxsize]; Ifstream Fin ("Input.txt"); if( !Fin.is_open ()) {cout<<"Open File Error"<<Endl; return 0; } intnum,n=0; while( !fin.eof ()) {Fin>>num; if(Fin.good ()) {A[n++] =num; } }}
"Problem"
Using the above code, you will enter more than one number at the end. The loop is determined by the judgment, EOF, whether the end of the file is terminated, but it will be a number of long. Searched the relevant questions on the Internet. This is probably the reason:
This is because the C + + input and output stream to determine the end of the way is different, according to: when the fin>>num can not read the data, can not find the end of the file, this will be the input file stream set the end of the file flag, that is, the EOFBIT flag, the participants return true. If NUM is the last number in the file, then after reading the number, Eofbit is not immediately set, because the last number can be entered normally, the fin flow will assume that the file has not reached the end, so the while loop fin.eof () is false, but also to perform a , this is the data has been read, so continue to fin>>num, there will be more than one number, which may be the most at the end of a number repeated, or other strange numbers, this time fin to find the end of the file, then set the Eofbit flag, jump out of the loop, But I've read more than one extra number before.
To put it simply, if Fin is reading the last number, EOF () is FALSE, and when the last digit is read in, the fin input is used again to find that EOF () is true at the end of the file.
"Solutions"
(1)
int num,n=0;
while (!fin.eof ())
{
fin>>num;
if (Fin.good ())
{
a[n++] = num;
}
}
(2)
int num,n=0;
while (!fin.eof ())
{
fin>>num;
if (Fin.fail ())
{
a[n++] = num;
}
}
(3)
The Peek function is only available for characters, that is, the char type, for the STR type, and int type, I have tried not to, or will be one.
char c;
while (Fin.peek ()!=eof)
{
Fin >> C;
cout << C;
}
About EOF for C + +