Home C++ Reading from a file in C++

Reading from a file in C++

In this example, we will show you how to open and read the contents of a file, in C++.

Example

In this example we open a file called fileexample.txt

The contents of this file is

This is a test file with some contents to read.
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
    cout << "how to read the contents from a file\n";

    //declaration of a string variable
    string myString;

    // creating a variable for file handling.
    ifstream inFile;

    //open file in same path
    inFile.open("fileexample.txt");

    cout << "Contents of the file is: \n\n";

    // printing the file contents word by word
    while(inFile>>myString)
        cout << myString << " ";
    
    cout << "\n";

    // close the file.
    inFile.close();

    return 0;
}

When compiled and run I saw this

how to read the contents from a file
Contents of the file is:

This is a test file with some contents to read.

--------------------------------
Process exited after 0.03671 seconds with return value 0
Press any key to continue . . .

You may also like