How to read text file

Submitted by:Pitter Alderson

Date added:04 May, 2013


How to read text file and print its contents to the console line by line.

Tags: read text file

Code Snippet:

#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
} else
// otherwise print a message
cout << "ERROR: can't open file." << endl;
return 0;