I have written a very little program that adds two integers:
#include <iostream>
using namespace std;
int inpInt() { //ask for an input in integer format
int number = 0;
cin >> number;
while (!cin) { //keep asking if the input was not an integer
cin >> number;
}
return number;
}
int main() {
int summand1, summand2, sum;
cout << "Summand 1: "; summand1 = inpInt();
cout << "Summand 2: "; summand2 = inpInt();
sum = summand1 + summand2;
cout << "Sum: " << sum << "\n";
}
The problem is that when I do not enter an integer, I am trapped in an infinite loop where I cannot enter neither an integer nor anything else. The strange thing is that when I include the integer testing loop in main(), the code works.
Thank you very much for any help!
You have to explicitly clear cin and ignore newlines (newline appears when you hit return)
int inpInt() { //ask for an input in integer format
int number = 0;
while (!(cin >> number)) {
cin.clear(); // clear cin
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore new lines. see: http://www.cplusplus.com/reference/istream/istream/ignore/
}
return number;
}
int main() {
int summand1, summand2, sum;
cout << "Summand 1: "; summand1 = inpInt();
cout << "Summand 2: "; summand2 = inpInt();
sum = summand1 + summand2;
cout << "Sum: " << sum << "\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With