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

[ad_1]

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.

2

[ad_2]

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