C++ ifstream Read a file before the EOF has been read.

Introduction

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()/*from w w w  .  j a va 2  s.  c om*/
{
   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;
}



PreviousNext

Related