Read text file line by line - C++ File Stream

C++ examples for File Stream:Text File

Description

Read text file line by line

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()// w w w .  ja  v a  2s .  c  o  m
{
   string filename = "prices.dat";
   string line;
   ifstream inFile;
   inFile.open(filename.c_str());
   if (inFile.fail())  // check for successful open
   {
      cout << "\nThe file was not successfully opened\n Please check that the file currently exists." << endl;
      exit(1);
   }
   // Read and display the file's contents
   while (getline(inFile,line))
      cout << line << endl;
   inFile.close();
   return 0;
}

Related Tutorials