Guest User

Untitled

a guest
Oct 17th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // sumafile.cpp -- functions with an array argument
  2. #include <iostream>
  3. #include <fstream> // file I/O support
  4. #include <cstdlib> // support for exit()
  5.  
  6. const int SIZE = 60;
  7.  
  8. int main()
  9. {
  10.     using namespace std;
  11.    
  12.     char filename[SIZE];
  13.     ifstream inFile; // object for handling file input
  14.    
  15.     cout << "Enter name of data file: ";
  16.     cin.getline(filename, SIZE);
  17.     inFile.open(filename); // associate inFile with a file
  18.    
  19.    
  20.     if (!inFile.is_open()) // failed to open file
  21.     {
  22.         cout << "Could not open the file " << filename << endl;
  23.         cout << "Program terminating.\n";
  24.         exit(EXIT_FAILURE);
  25.     }
  26.    
  27.    
  28.     double value;
  29.     double sum = 0.0;
  30.     int count = 0; // number of items read
  31.    
  32.     inFile >> value; // get first value
  33.    
  34.     while (inFile.good()) // while input good and not at EOF
  35.     {
  36.         ++count; // one more item read
  37.         sum += value; // calculate running total
  38.         inFile >> value; // get next value
  39.     }
  40.    
  41.    
  42.     if (inFile.eof())
  43.         cout << "End of file reached.\n";
  44.     else if (inFile.fail())
  45.         cout << "Input terminated by data mismatch.\n";
  46.     else
  47.         cout << "Input terminated for unknown reason.\n";
  48.    
  49.    
  50.     if (count == 0)
  51.         cout << "No data processed.\n";
  52.     else
  53.     {
  54.         cout << "Items read: " << count << endl;
  55.         cout << "Sum: " << sum << endl;
  56.         cout << "Average: " << sum / count << endl;
  57.     }
  58.    
  59.    
  60.     inFile.close(); // finished with the file
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment