/* program demonstrating simple input from a file * * it just reads lines numbers in from a file and averages them */ #include #include #include #include // for exit() #include using namespace std; int main() { // declare the stream object and connect it to input file ifstream fin("scores.txt"); // check for problems (fin is null if there was a problem) if (!fin) { cerr << "could not open scores.txt\n"; exit(-1); } // get the sum by reading through the file int counter=0; int val, valSum=0.0; while (fin >> val) { // >> will return null when EOF is reached valSum += val; counter++; } // if we had more than 0 entries, print the sum if (counter) { cout << counter << " numbers found"; cout << " with an average of " << valSum / (double)counter << endl; } else cout << "no values found in file." << endl; fin.close(); cout << "hit a key."; getch(); }