Source of errors_if.cpp


  1: //errors_if.cpp
  2: //Illustrates use of if statements to handle errors encountered
  3: //in attempting to read data from a file input stream.

  5: #include <iostream>
  6: #include <fstream>
  7: using namespace std;

  9: #include "utilities.h"
 10: using Scobey::Pause;

 12: int main()
 13: {
 14:     cout << "\nThis program tries to open a file input stream, "
 15:         "then read two integers from it,\nand display them. If it "
 16:         "does not succeed, it reports an error and terminates.\n";
 17:     Pause();

 19:     ifstream inFile("exceptions.in");
 20:     if (!inFile.is_open())
 21:     {
 22:         Pause(0, "Error: Could not open input data file "
 23:             "\"exceptions.in\".\nMake sure file exists, "
 24:             "and run program again.");
 25:         return 1;
 26:     }

 28:     int first, second;
 29:     inFile >> first >> second;
 30:     if (!inFile)
 31:     {
 32:         if (inFile.eof())
 33:             Pause(0, "Error: End of file reached before "
 34:             "all data read.\nProgram now terminating.");
 35:         else
 36:             Pause(0, "Error: Something wrong with input data."
 37:             "\nProgram now terminating.");
 38:         return 2;
 39:     }
 40:     cout << "The data in the file was successfully read. "
 41:         "\nThe two values in it were: \n"
 42:         << "   first: "  << first
 43:         << "   second: " << second << "\n\n";
 44:     Pause();
 45: }