C++ Reading an unknown number of integers to cin and outputting the sum

The underlying problem here is that you don’t know in advance how many integers are going to come in, so you can’t use that for loop — there’s no sensible value for numbers.

Instead, keep reading values until the end of the input:

while (std::cin >> i)
    sum += i;

When the attempted read eventually fails, the while loop will exit.

Browse More Popular Posts

Leave a Comment