0
In C++, if the user types something different from a number, I want to print on the screen: "Invalid input. Type a number." How?
If the user types a letter instead of a number, for example, it won't work. I want to know how can I print on the screen that he's not using the program properly. What's the command that I should use in C++ to make the compiler recognize that the input is invalid then show my message?
1 Réponse
+ 3
When the input stream is unable to extract data, for example when a string is entered but an integer expected, it sets up an internal error flag that you can check easily.
https://en.cppreference.com/w/cpp/io/basic_ios/fail
Sample:
int i{ 0 }; std::cin >> i;
if ( std::cin.fail() )
{
std::cout << "Bad Input!";
}
else
{
std::cout << i;
}