/* Filename: readfile.cpp Author: Br. David Carlson; Br. Isidore Minerd Date: January 8, 2000 Modified: June 26, 2000; August 22, 2001; July 16, 2009 This program reads floating point numbers from the text file readfile.txt and finds and prints their average. The text file readfile.txt should have the numbers on separate lines or separated by blank space. Tested with: Microsoft Visual C++ 6.0 Microsoft Visual C++ .NET Microsoft Visual Studio 2008 g++ under Linux */ #include #include // needed for files using namespace std; int main(void) { fstream InFile; float Num, Total; int Count; InFile.open("readfile.txt", ios::in); if (InFile.fail()) { cout << "Could not open readfile.txt" << endl; exit(1); } Count = 0; Total = 0.0; InFile >> Num; while (! InFile.fail()) { Total = Total + Num; Count++; InFile >> Num; } if (Count > 0) cout << "Average is " << Total / Count << endl; else cout << "No data given" << endl; InFile.close(); return 0; }