The type of data to be retrieved from the input is automatically determined by std::cin, which writes it to the specified variable. We can use the (!) NOT operator to check the overloaded cin. If the variable type and input data type differ, std::cin is in an unstable state. This feature allows us to determine whether the given data is a number or not.
Input validation and error handling can be used together in C++ to generate an error when the input is not a number. To determine whether the input was successful, one popular option is to utilize the fail function in combination with the std::cin input stream.
Approach:
- To get started, use std::cin to read the input and check for input errors.
- Use std::cin.clear function to clear the error condition and use std::cin.ignore to ignore the rest of the input line if an error is found.
- Finally, if an error is found, print an error message.
Example 1:
// C++ program to Output Error When Input Isn't a Number
#include <iostream>
#include <limits>
using namespace std;
int main()
{
// Prompt the user to enter a number
cout << "Please enter a number: ";
int num;
// Keep reading input until a valid number is entered
while (!(cin >> num)) {
// Clear the error state
cin.clear();
// Ignore the rest of the incorrect input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Prompt the user again
cerr << "Error: That was not a number. Please "
"enter a number: ";
}
// Output the entered number
cout << "You entered the number: " << num << endl;
return 0;
}
Output:
Complexity Analysis:
Time Complexity: O (1)
Space Complexity: O (1)
Example 2:
#include <iostream>
#include <limits>
int main() {
double number;
std::cout << "Enter a number: ";
std::cin >> number;
if (std::cin.fail()) {
std::cin.clear(); // Clear the fail flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard the input
std::cerr << "Error: Input is not a number." << std::endl;
} else {
std::cout << "You entered: " << number << std::endl;
}
return 0;
}
Output:
Complexity Analysis:
Time Complexity: O (1)
Space Complexity: O (1)