Need help with a C++ assignment? Get affordable C++ homework help.

How to read text file code snippet

Summary

Source code of C++ program, demonstrating how to read text file and print its contents to the console line by line.

Source code

C++: reading_text_file.cpp

#include <fstream>

#include <iostream>

#include <string>

 

using namespace std;

 

int main() {

      // a string to store line of text

      string textLine;

      // try to open a file

      ifstream ifs("sample_file.txt", ifstream::in);

      if (ifs.good())   { // if opening is successful

            // while file has lines

            while (!ifs.eof()) {

                  // read line of text

                  getline(ifs, textLine);

                  // print it to the console

                  cout << textLine << endl;

            }

            // close the file

            ifs.close();

      } else

            // otherwise print a message

            cout << "ERROR: can't open file." << endl;

 

      return 0;

}

 

Sample run

C/C++

Hello, I am sample file.
Line 1
Line 2
Line 3
The end.