bowstring bowstring -3 years ago 56
C++ Question

C++ input in the while statement

#include <iostream>
int main()
{
int sum = 0, value = 0;
while (std::cin >> value)
sum += value;
std::cout << sum << std::endl;
return 0;
}


When I give 1 2 3 q in terminal, then output is 6. But when i give 1 2 3 4.0, then output is 10.

Why does this program print 10 not 6?

Answer Source

The operator >> for the type int reads digits until a non-digit is encountered.

So the condition

while (std::cin >> value)

evaluates to false when the dot is encountered in the buffer.

1 2 3 4 are valid numbers. The first non-valid symbol is '.'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download