MC logo
Read-To-End Average
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Counted Average Example] [For Loop Average] [For Loops] [Read-To-End Average] [Reading In the While Test] [Counting Example 1] [Counting Example 2] [Counting Example 3] [Counting Example 4] [Counting Example 5] [Watch Out For This] [Switch] [Switch Using Break] [Break and Continue] [Change Adder]
#include <iostream>
using namespace std;

        int cnt = 0,            // Count of numbers read. 
            tot = 0;            // Total of numbers read.
        int num;                // Input number.

        // Read all the numbers (until a read fails and the stream
        // turns bad.)
        cin >> num;
        while(cin.good()) {
                tot += num;
                cin >> num;

        /* Print the average. */
        if(cnt > 0)
                cout << "Average is " << (double)tot /  (double)cnt << endl;
                cout << "No numbers." << endl;

This version does not require telling the program ahead of time how many values will be input. It reads until a read fails, which happens at the end of the input stream, or upon a data error.