The data type to be fetched from the input is automatically detected by std::cin, which then stores it in the designated variable. By employing the (!) logical NOT operator, we can examine the cin overload. In case there is a mismatch between the variable type and the input data type, std::cin enters an inconsistent state. This functionality enables us to ascertain whether the provided data is numeric or not.
Input validation and error handling can be effectively combined in C++ to trigger an error message in case the input is not a numeric value. A common approach to verify the success of the input is by leveraging the fail method along 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)