I'm not a big fan of the std::getline()
and then use std::istringstream
approach: streams aren't free to create. At the very least, the inner `std::istringstream should be constructed once and then be reset, even though this requires to clear the flags:
std::istringstream iss;
for (std::string line; std::getline(std::cin, line); ) {
iss.clear();
iss.str(line);
// ...
}
The call to iss.clear()
resets the stream's error flags which get set to eventually indicate that there is no more data. With iss.str(line)
the string stream's internal data is set.
Instead of creating or setting an std::istringstream
I would arrange for the newline to set the input stream to be false, i.e., to have std::ios_base::failbit
set. For the advanced approach to do so, I'd change the definition of whitespace for the std:ctype<char>
facet in the std::locale
used by the stream. However, that's shooting the big guns! For the task at hand, a simple manipulator used before each input can be used to a similar effect:
#include <iostream>
#include <cctype>
using namespace std;
std::istream& skipspace(std::istream& in) {
while (std::isspace(in.peek())) {
int c(in.peek());
in.ignore();
if (c == '\n') {
in.setstate(std::ios_base::failbit);
break;
}
}
return in;
}
int main() {
int sum(0);
while (std::cin >> sum) {
for (int value; std::cin >> skipspace >> value; ) {
sum += value;
}
std::cout << "sum: " << sum << "\n";
std::cin.clear();
}
return 0;
}
Most of the magic is in the manipulator skipspace()
: it skips whitespace until either the end of the stream is reached or a newline is consumed. If a newline is consumed, it puts the stream into failure state by setting the flag std::ios_base::failbit
.
The loop computing the sum simply reads the first value. If this fails, e.g., because a non-integer is found, the input fails and no further output is generated. Otherwise whitespace is skipped using the skipspace()
followed by reading the next value. If either of these fails, the current sum
is printed and the stream is cleared for the next sum to be read.