How to read from a file in C++

By chris

This is a basic example how to read from a file in C++ without much error checking or anything. If you want to have a look at the ifstream reference, it’s here.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  ifstream file;
  string line;
  file.open("./myfile.txt");
  if (!file.is_open()){
     cerr << "Oops. Could not open file." << endl;
     return -1;
  }
  while (!file.eof()) {
     getline(file, line);
     cout << line << endl;
  }
  file.close();
}

Leave a Reply