C + + Text data read

Source: Internet
Author: User

When reading text data, its corresponding process and write quite similar, but there are some differences, after all, is two different functions.

1. Add the necessary header files: #include <fstream>, #include <cstdlib>.

2. Define the appropriate array to store the name of the file.

3. Define the appropriate variables to store the data written by the file.

4. Create a Ifstream object.

5. Associate the Ifstream with a text file.

6. Test whether the file is open properly.

7. Write data using the Ifstream object and the << operator.

8. Close when you are finished using the Ifstream object.

As an example, a program that iterates through all the data and computes the characters is used as an instance:

#include <iostream> #include <fstream>//file I/O support#include <cstdlib>//support for Exitconst int SIZE = 60;int Main () {using namespace Std;char Filename[size];char ch;ifstream infile;//object for handing file inputcout << "Enter Name of data file:"; Cin.getline (filename,size); Infile.open (filename);//Associate InFile with a Fileif (! Infile.is_open ())//failed to open file{cout << ' Could not open the file ' << filename << endl;cout < < "program terminating.\n"; exit (exit_failure);} int sum = 0;//number of items Readinfile >> ch;while (Infile.good ())//While input good not at Eof{sum++;infile > > ch;} cout << sum << "characters in" << filename << endl;infile.close ();//Done with the Filereturn 0; }

when the test file is open normally, if the open fails, it is necessary to terminate the program's operation, here to use the # include <cstdlib> header file, the corresponding statement in the program EXIT (exit_failure); with it, Mother no longer have to worry about the file open failed to do.

When traversing data in a file, the good () method is a good choice, because failed (), EOF (), bad () in the traversal has its own wonderful place (specifically please Baidu, do not do the detailed).

C + + Text data read

Related Article

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.