How to Output Error When Input Isn’t a Number in C++?
Last Updated :
19 Feb, 2024
In C++, when taking user input, we may need to validate that it is a number and output an error if it is not. In this article, we will learn how to output an error when the input isn’t a number in C++.
For Example,
Input:
Enter a Number: G
Output:
Error: That was not a number.
Output Error When Input Isn’t a Number in C++
The std::cin automatically deduces the type of data that is to be extracted from the input and puts it into the specified variable. We can use the (!) NOT operator with cin which is overloaded to check the state of the cin. The state of std::cin is set to bad when the input data type does not match the variable type. We can use this property to check whether the given data is a number or not.
Approach
To output an error when the input entered by the user is not a number do the following:
- First, try to read the input using std::cin and check for input failure.
- If an error is detected, use
std::cin.clear()
to clear the error state, and std::cin.ignore()
to ignore the rest of the input line.
- Finally, output an error message if an error is detected.
C++ Program to Output Error When Input isn’t Number
The below example demonstrates how we can check and output an error when the input isn’t a number in C++.
C++
#include <iostream>
#include <limits>
using namespace std;
int main()
{
cout << "Please enter a number: " ;
int num;
while (!(cin >> num)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
cerr << "Error: That was not a number. Please "
"enter a number: " ;
}
cout << "You entered the number: " << num << endl;
return 0;
}
|
Output:
Please enter a number: g
Error: That was not a number. Please enter a number: 5
You entered the number: 5
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...