How to handle wrong data type input
The reason the program goes into an infinite loop is because std::cin
's bad input flag is set due to the input failing. The thing to do is to clear that flag and discard the bad input from the input buffer.
//executes loop if the input fails (e.g., no characters were read)
while (std::cout << "Enter a number" && !(std::cin >> num)) {
std::cin.clear(); //clear bad input flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
std::cout << "Invalid input; please re-enter.\n";
}
See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.
Another way would be to get the input as a string and convert it to an integer with std::stoi
or some other method that allows checking the conversion.
How to Handle Exception of wrong data type input but the variable was not an object in Java
Integer.parseInt
will throw a NumberFormatException
. Catch it, this is your case for "Integer please!"
.
Exception handling - how to handle invalid datatype in user input?
- Get input from user by
raw_input()
(Python 2) orinput()
(Python 3). Type
of variablename
isstring
, so we have to use string method to valid user enter string.- Use
isalpha()
string method to check user entered string is valid or not.
code:
name = raw_input("Enter your Last Name:")
if not name.isalpha():
print "Enter only alpha values."
output:
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:123
Enter only alpha values.
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek 123
Enter only alpha values.
Other string methods to check user string is integer or alpha or both
>>> "123".isalnum()
True
>>> "123a".isalnum()
True
>>> "123abc".isalnum()
True
>>> "123abc".isalpha()
False
>>> "123abc".isdigit()
False
>>> "123".isdigit()
True
>>> "123".isalpha()
False
By Type conversion and Exception method
e.g. for invalid input:
>>> a = "123a"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
User string is not number
e.g. for valid input:
>>> a = "123"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
>>> print a
123
>>> type(a)
<type 'int'>
>>>
Ask user to enter value again and again if user enter invalid value.
code:
while 1:
try:
age = int(raw_input("what is your age?: "))
break
except ValueError:
print "Enter only digit."
continue
print "age:", age
output:
vivek@vivek:~/Desktop/stackoverflow$ python 5.py
what is your age?: test
Enter only digit.
what is your age?: 123test
Enter only digit.
what is your age?: 24
age: 24
How I get the right exception for wrong Datatype input?
You only need the following
int x;
Console.WriteLine("Enter the first number: ");
while (!Int32.TryParse(Console.ReadLine(), out x))
Console.WriteLine("Invalid input! Try again");
Console.WriteLine($"You had one job and it was a success : {x}");
Here is the deal
Console.ReadLine()
returns a string, Int32.TryParse(
returns true
or false
if it can parse a string
to an int
.
The loop will continually loop while Console.ReadLine()
cannot be parsed to an int
As soon as it can, the loop condition is not met and execution continues to the last Console.WriteLine
prevent users from entering wrong data types
you can read with scanf("%d")
and if the user enter a string containing a non numeric character then you have to clean the stdin buffer before reading again with scanf("%d")
.
when you clean the stdin, you will stop the infinite loop
Use the following function to clean your stdin
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
And The read of your integer from stdin could be done in this way:
char c;
do
{
printf("\nEnter an integer from 5 to 20: ");
} while (((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) || rows<5 || rows>20);
Related Topics
Make_Unique and Perfect Forwarding
Can Modern X86 Hardware Not Store a Single Byte to Memory
Returning Unique_Ptr from Functions
Static Initialization Order Fiasco
Why Use Iterators Instead of Array Indices
Why Copy Constructor Is Not Called in This Case
Does the Default Constructor Initialize Built-In Types
Opengl Object in C++ Raii Class No Longer Works
Do Built-In Types Have Default Constructors
"Undefined Reference To" Errors When Linking Static C Library With C++ Code
How to Mix Swift With C++? Like the Objective-C .Mm Files
Is (4 ≫ Y ≫ 1) a Valid Statement in C++? How to Evaluate It If So
Function Passed as Template Argument
Good Input Validation Loop Using Cin - C++
What Happens to Global and Static Variables in a Shared Library When It Is Dynamically Linked