/* Filename: readfile2.cpp Author: Br. David Carlson; Br. Isidore Minerd Date: January 8, 2000 Modified: June 26, 2000; August 22, 2001, October 26, 2004; 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; // Function prototype: void ProcessFile(fstream & fs); int main(void) { fstream InFile; InFile.open("readfile.txt", ios::in); if (InFile.fail()) { cout << "Could not open readfile.txt" << endl; exit(1); } ProcessFile(InFile); InFile.close(); return 0; } /* Given: fs A text file of floats, one per line, already opened for input. Task: To read the floats from fs and compute and print their average. Return: Nothing. */ void ProcessFile(fstream & fs) { float Num, Total; int Count; Count = 0; Total = 0.0; fs >> Num; while (! fs.fail()) { Total = Total + Num; Count++; fs >> Num; } if (Count > 0) cout << "Average is " << Total / Count << endl; else cout << "No data given" << endl; }