Input Validation in C++

Input Validation in C++

In this post, we will see about Input validation in C++.

How to check user input in C++?

To stop the user from entering wrong data in the field, we can use input validation methods in C++. It is a process for checking if the data entered by a user meets some criteria or not. This process can also be broken mainly into two types: numeric and string.

String Input Validation In C++

With this technique, we can accept all user input as a string, and then we can reject or accept the string as per the requirements. Example: When we ask a user to enter a phone number, then we want to ensure that the user enters only ten digits. To implement this in C++, it has a regular expression library which can make input validation in C + + a little easier.

In C++, there are numerous functions which can help in determining if the characters entered are numbers or letters. The functions mentioned below can be used with the ‘cctype’ header.

Functions:

Function Description
isalnum(int) It will return non-zero if the parameter passed is a digit or a letter.
isalpha(int) It will return non-zero if the parameter passed is a letter.
iscntrl(int) It will return non-zero if the parameter passed is a control character.
isdigit(int) It will return non-zero if the parameter passed is a digit.
isgraph(int) It will return non-zero if the parameter passed is a printable character that is not whitespace.
isprint(int) It will return non-zero if the parameter passed is printable character (Including the whitespaces).
ispunct(int) It will return non-zero if the parameter passed is either alphanumeric or whitespace.
isspace(int) It will return non-zero if the parameter passed is whitespace.
isxdigit(int) It will return non-zero if the parameter passed is a hexadecimal digit(0-9,A-F,a-f).

Code:

Input:

Enter the name of the person: Shashank Jain
Enter the name of the person: Java2Blog
Enter the name of the person: Test123

Output:

The name entered is Shashank Jain
Enter a Valid Name!!
Enter a Valid Name!!

Note: all_of function will return true if pred returns true for the elements in the range.

Syntax:

Numeric Input Validation in C++

To handle numeric inputs, we can use an extraction operator to check if the user entered the numeric type input or not. With the help of fail(), we can check if the user entered numeric input or not.

Code:

Input:

Enter the age: 35
Enter the age: Java2Blog
Enter the age: 23abc

Output:

The age you entered is: 35
Enter valid age!!
Enter valid age!!

Conclusion

In this article, we learnt different ways to implement input validation in C++. Any method can be used as per the requirements.
Happy Learning!!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *