sumafile.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. const int SIZE = 60;
  6. int main()
  7. {
  8. using namespace std;
  9. char filename[SIZE];
  10. ifstream inFile; // object for handling file input
  11. cout << "Enter name of data file: ";
  12. cin.getline(filename, SIZE);
  13. inFile.open(filename); // associate inFile with a file
  14. if (!inFile.is_open()) // failed to open file
  15. {
  16. cout << "Could not open the file " << filename << endl;
  17. cout << "Program terminating.\n";
  18. // cin.get(); // keep window open
  19. exit(EXIT_FAILURE);
  20. }
  21. double value;
  22. double sum = 0.0;
  23. int count = 0; // number of items read
  24. inFile >> value; // get first value
  25. while (inFile.good()) // while input good and not at EOF
  26. {
  27. ++count; // one more item read
  28. sum += value; // calculate running total
  29. inFile >> value; // get next value
  30. }
  31. if (inFile.eof())
  32. cout << "End of file reached.\n";
  33. else if (inFile.fail())
  34. cout << "Input terminated by data mismatch.\n";
  35. else
  36. cout << "Input terminated for unknown reason.\n";
  37. if (count == 0)
  38. cout << "No data processed.\n";
  39. else
  40. {
  41. cout << "Items read: " << count << endl;
  42. cout << "Sum: " << sum << endl;
  43. cout << "Average: " << sum / count << endl;
  44. }
  45. inFile.close(); // finished with the file
  46. // cin.get();
  47. return 0;
  48. }