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 numbers 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>

int main()
{
    int i;

    while (true) {
        std::cin >> i;
        if (std::cin.eof())
            break;
        std::cout << i << std::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