There are a number of issues with your code: the most obvious is
that you are using the results of input without first checking
whether the input succeeded, and that you're using the character
encoding as an integral value.
The most idiomatic way of writing this would be something like:
int input;
while ( std::cin >> input ) {
sum += input;
}
This isn't perfect; if the use inputs a letter, then this treats
it as end of file. A possibly more robust solution would be:
std::string line;
while ( std::getline( std::cin, line ) ) {
std::istringstream parse( line );
int input;
if ( parse >> input >> std::ws && parse.get() == EOF ) {
sum += input;
} else {
std::cerr << "not a number: " << line << std::endl;
}
}
This assumes (requires) one number per line, which is a simple
format, and easy to verify and to resynchronize in case of
error. If line endings are without meaning, resynchronizing
becomes more complex.
Both of these solutions input until end of file, which is the
most nature solution (rather than looking for a q
). If you
insist on ending with a specific token, and the input is line
oriented, you can do something like:
std::string line;
while ( std::getline( std::cin, line ) && notEndToken( line) ) {
// ...
}
with the same loop body as above. The function notEndToken
could be as simple as return line == "q";
, but more likely,
you'll want to skip spaces, allow upper and lower case, etc., so
it makes more sense to put it into a separate function. (Of
course, you still need to check that the input has succeeded.
Just because you're expecting a special token doesn't mean that
you'll get one. You have to handle end of file correctly in
every case.)