#include <iostream>
int main ()
{
int sum = 0, value;
std::cout << "Input some numbers." << std::endl;
while (std::cin >> value) sum += value;
std::cout << "The sum is: " << sum << std::endl;
std::cin >> value;
return 0;
}
From what I can tell this is more or less identical to a program in C++ Primer, except for the std::cout prompt and the std::cin at the end that allows me to see the final output (yes, I know there are other ways, but surely it can't matter much?).
According to the book this should allow me to simply enter as many numbers as I want to and have the program add them up. The problem is that the only way that I can seem to get the program to stop asking me for more numbers is to input anything that's not an integrer, but that just shuts down the command prompt instantly.
So what gives? I've read through the part in the book a couple of times now and can't seem to find the issue.
Edit: So it seems to actually finish the program if I make an invalid input, but the only way I've found of making the command prompt stay up long enough for me to read the result is by using the system ("PAUSE") statement.
So I guess my main question now is why the program won't let me make inputs after the while statement.
If cin got an input action failed it wouldn't allow other.
Having the program expecting invalid input is not a good design, you should read http://www.cplusplus.com/forum/articles/6046/
Thank you, though I expect/hope that C++ Primer teaches me better ways of doing this later.
Obviously it's not good design, but this is just practice for me. :)
#include <iostream>
int main ()
{
int sum = 0, value;
std::cout << "Input some numbers." << std::endl;
while (std::cin >> value) sum += value;
std::cout << "The sum is: " << sum << std::endl;
std::cin.clear(); // http://www.cplusplus.com/reference/iostream/ios/clear/
std::cin.sync(); // http://www.cplusplus.com/reference/iostream/istream/sync/
std::cin >> value;
return 0;
}