Read a file before the EOF has been read. - C++ File Stream

C++ examples for File Stream:File Operation

Description

Read a file before the EOF has been read.

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()// w w  w  .  ja va 2 s .  c o m
{
   string filename = "prices.dat";
   string descrip;
   double price;
   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
   inFile >> descrip >> price;
   while (inFile.good()) // check next character
   {
      cout << descrip << ' ' << price << endl;
      inFile >> descrip >> price;
   }
   inFile.close();
   return 0;
}

Related Tutorials