Read data from the file and use the EOF function to determine whether the file is finished. However, the last character or number of the file is read once more. For example, the following code:
Ifstream infile; infile. Open ("D: \ a.txt"); If (! Infile. is_open () // open the file {cout <"failed" <Endl;} else {string STR; while (! Infile. EOF () {infile> STR; // read the memory cout <STR <Endl ;}} infile. Close (); infile. Clear ();
Output in the console, once more. After analysis, I personally understand that the EOF method checks whether the content in the stream is a Terminator. When the above while is run to the Terminator, while (! Infile. EOF () is the last retained information in the infile stream. Therefore, the final character is read into STR and cannot be read. Therefore, the information stored in STR is the last time, and then output again.
The code is changed to the following:
Ifstream infile; infile. Open ("D: \ a.txt"); If (! Infile. is_open () // open the file {cout <"failed" <Endl;} else {string STR; while (! Infile. EOF () // judge whether the stream is saved as a terminator {infile> STR; // read into the memory if (infile. fail () {break;} elsecout <STR <Endl ;}} infile. close (); infile. clear ();
Check the read data before output. If the read fails, no output is performed.
If there are any unreasonable reasons, please let me know. Thank you!