I have an assignment to create a menu-based program to calculate area of several shapes using user-defined function. My code creates an infinite loop when a user input a cha
With float r1; cin >> r1;
and non-numeric input, there is nothing consumed from input. Repeating cin >> r1
results in an endless loop.
What to do?
cin >> r1
was successful: if (cin >> r1) { /* process r1 */ }
else { cin.clear(); cin.ignore(); }
std::ios::clear()
Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.
std::istream::ignore()
Extracts and discards characters from the input stream until and including delim.
Example:
#include <iostream>
#include <limits>
int main()
{
double value = 0.0;
for (;;) {
std::cout << "Value: ";
if (std::cin >> value) {
break; // success -> bail out of loop
} else {
std::cerr << "Wrong input!\n";
std::cin.clear(); // reset state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // consume wrong input
}
}
std::cout << "Value: " << value << '\n';
return 0;
}
Output:
Value: Hello↵
Wrong input!
Value: 1.23↵
Value: 1.23
Live Demo on coliru