Exercise: Sum of Integers Coming From cin

Description

Write a program (lets call it sum-ints) that

  • reads a sequence of integer numbers from standard input (std::cin), line by line

  • store them in a std::vector<int>

  • outputs the sum of these number when standard input’s end is reached [1]

The program is typically called this way:

$ ./sum-ints
666
42
7
^D             <--- EOF on standard input
715

Note

The following demo program shows how to handle the End-Of-File condition. It reads numbers from standard input (and echoes them to standard output) until EOF is reached.

#include <iostream>

using namespace std;


int main()
{
    int i;

    while (true) {
        cin >> i;
        if (cin.eof())
            break;
        cout << i << endl;
    }
    
    return 0;
}

Footnotes

Dependencies

cluster_cxx03 C++ cluster_cxx03_exercises_misc Exercises: Miscellaneous cxx03_exercises_misc_sum_integers_from_stdin Exercise: Sum of Integers Coming From cin