Hi all,
i was trying to type the same program from a book that does the following:
Program requests to enter a number 0 -100.
The program checks if the entry is valid, if not, the faildbit should be cleared (cin.clear) and invalid entry discarded (cin.ignore).
if itry this code and enter a text instead of a number, i run into an endledd loop of "Invalid number. Try again"
Code:
while (true) {
cout << "Enter a number between 0 - 100" << endl;
cin >> d;
if (!cin.good()) {
cout << "Invalid input. Try again" << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
continue;
}
if (d < 0 || d > 100) {
cout << "Wrong range. Try again" << endl;
}
else {
cout << "You entered " << d << endl;
break;
}
}
return 0;
checking the book again, i saw i switched 2 lines. i should ignore than clear
Code:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
i dont' unterstand how the order of those 2 lines, is having this impact? it seems for me also correct, to discard first and clear the failbits.
i wouls be gratefull for any hints