File Read Information, EOF () Multi-read Problem

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.