Wednesday, March 16, 2016

How To Read a Text File in C++

This simple example shows you how to load a text file the user enters as console input and print out the results to the screen.

#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {

    //Get File    
    cout << "Please enter a file to open: ";
    //Filename string
    std::string filename;
    cin >> filename;
    printf ("Attempting to open %s\n", filename.c_str());
    //Make an ifstream construct with filename
    ifstream myfile(filename.c_str());
    //string to hold line contents
    string line;
    if (myfile.is_open())
        while ( getline (myfile,line) ) //iterate through lines
              cout << line << '\n';  //print line out
        myfile.close(); //close when done
    else cout << "Failed to find file";
    return 0;

Sample Console:

Please enter a file to open: test.txt
Attempting to open test.txt
Press [Enter] to close the terminal ...


Post a Comment