1.4.3. Reading an Unknown Number of Inputs

In the preceding sections, we wrote programs that summed the numbers from 1 through 10. A logical extension of this program would be to ask the user to input a set of numbers to sum. In this case, we won’t know how many numbers to add. Instead, we’ll keep reading numbers until there are no more numbers to read:

#include <iostream>int main(){    int sum = 0, value = 0;    // read until end-of-file, calculating a running total of all values read    while (std::cin >> value)        sum += value; // equivalent to sum = sum + value    std::cout << "Sum is: " << sum << std::endl;    return 0;}

If we give this program the input

3 4 5 6

then our output will be

Sum is: 18

The first line inside main defines two ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.