I'm trying to write in C++ a function (leggiInteroEstrIncl
) that prompts the user to type by keyboard an integer number included in a given range (between minimo
and massimo
).
Following is the function I wrote and then a statement, in the main()
, to invoke it:
#include <iostream>
using namespace std;
int leggiInteroEstrIncl(string stringaDaStampare, int minimo, int massimo) {
int numInserito = 0;
bool errore = false;
do {
errore = false;
cout << stringaDaStampare << " (un numero intero compreso tra " << minimo
<< " e " << massimo << " estremi inclusi): ";
try {
cin >> numInserito;
} catch (...) {
errore = true;
cout << "Hai inserito un numero non valido, prova ancora" << endl;
}
if (errore == false && (numInserito < minimo || numInserito > massimo)) {
errore = true;
cout << "Hai inserito un numero al di fuori dell'intervallo richiesto: "
<< minimo << " <-> " << massimo << endl;
}
} while (errore);
return numInserito;
}
int main() {
int number = 0;
number = leggiInteroEstrIncl(
"Inserire la cifra in Yen da ripartire in banconote e monete", 1, 30000);
system("pause");
return 0;
}
If I type a valid integer number which is not included in the specified range, this piece of software works and asks the user to type again, but if I type something which is not a number, for example the word "hello", this software goes in a sort of loop and doesn't stop to ask the user to type again.
Could you please tell me what is wrong with it?
Thank you