Use std::getline to read an input line and exit the loop when the line is empty.
#include<iostream> #include <sstream> int main() { int a = 0, h = 0; std::cout << "Enter numbers to be added:\n "; std::string line; std::cout << "\n" << h << " + "; while (std::getline(std::cin, line) && // input is good line.length() > 0) // line not empty { std::stringstream linestr(line); while (linestr >> a)// recommend better checking here. Look up std::strtol { h = h+a; std::cout << "\n" << h << " + "; } } return 0; }
And output:
Enter numbers to be added: 0 + 1 2 3 4 5 6 7 8 9 1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 +
Note that this allows multiple entries per line and looks pretty ugly, so OP is probably more interested in:
#include<iostream> int main() { long a = 0, h = 0; std::cout << "Enter numbers to be added:\n "; std::string line; std::cout << "\n" << h << " + "; while (std::getline(std::cin, line) && // input is good line.length() > 0) // line not empty { char * endp; // will be updated with the character in line that wasn't a digit a = std::strtol(line.c_str(), &endp, 10); if (*endp == '\0') // if last character inspected was the end of the string // warning: Does not catch ridiculously large numbers { h = h+a; } else { std::cout << "Very funny, wise guy. Try again." << std::endl; } std::cout << "\n" << h << " + "; } return 0; }
Output
Enter numbers to be added: 0 + 1 1 + 1 2 3 4 Very funny, wise guy. Try again. 1 + 2 3 + 44444 44447 + jsdf;jasdklfjasdklf Very funny, wise guy. Try again. 44447 + 9999999999999999999999 -2147439202 +
A0ina, which means that manually entering this integer would stop the loop, I can't see how it is desirable (besides,cin >> a;doesn't even return when you only press enter on my machine... how do you want to testafor a line end if the function blocks until you've entered something relevant?). I suggest you use Kay's answer (or RyanP's answer which is fine too) which has the intended behaviour (and even checks for invalid values). I don't get why they were downvoted.