![]() |
VOOZH | about |
In C++, when we’re expecting a certain type of input but the user enters a different type then such input is called incorrect data input and it can cause issues like unexpected behavior, program failures, or inaccurate results. In this article, we will learn how to handle wrong data type input in C++.
To handle wrong data type input, we can use a combination of std::cin.fail() and std::cin.clear(). The std::cin.fail() function returns true if the last input operation failed, and std::cin.clear() clears the error state of the cin object.
By using the below approach we can ensure that the program continues to take the input from a user until a valid input is entered, handling any wrong data type entered by the user.
The below program demonstrates how we can handle wrong data type inputs in C++.
Output
Enter an integer: adsafds
Invalid input! Expected an integer.
Enter an integer: !@fsgg
Invalid input! Expected an integer.
Enter an integer: 123
You entered: 123Time Complexity: O(N), where N is the maximum number of iterations to validate the input.
Auxiliary Space: O(1)