How do I do simple validation in C++?
What I mean is how can I make the program throw an error when a user enters an integer when a string is expected, and ask the user to re-enter until a string is entered.
Is there a simple way to do this?
Thanks
How do I do simple validation in C++?
What I mean is how can I make the program throw an error when a user enters an integer when a string is expected, and ask the user to re-enter until a string is entered.
Is there a simple way to do this?
Thanks
There is nothing in the standard C++ set of functionality that will "stop" a user from entering random digits when asked for a string. You will have to write some code to determine if the input is valid - for example check each character of the string to see if it's digits or not. Depending on the exact criteria, "no digits" or "must not be ONLY digits" or whatever, you will have to come up with the code to check it.
Useful functionality is isdigit, which requires #include <cctype>. There are other useful functions there, such as isalpha, isspace, etc.
And of course, to give an error message, you will need to use some suitable print function, and to repeat, use some do-while or while or similar construct.
Try to convert the string entered by user to an integer using std::strtol. If operation fails that means that what user entered is not a string representation of an integer (continue program execution). If operations succeeds that means that what user entered is a string representation of an integer. In this case ask a user for other input. Keep in mind that strol will successfully convert strings like 12345qwerty to an integer.
If you want to check if the entered string consists only of numerals you should iterate over all string characters and check if the are numerals using std::isdigit.