-2

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

user2768498
  • 155
  • 1
  • 2
  • 9
  • 2
    When user enters a string representation of an integer he enters a string. – Kolyunya Sep 11 '13 at 11:41
  • The user always inputs a string. What you want is to validate it and make sure that it is numerical and that it represents an integer. I think you can find all the info you need here: [link](http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c) – elnigno Sep 11 '13 at 11:44
  • Can you show an xample of expected, valid and ivalid input. – jrok Sep 11 '13 at 11:44
  • You can never "enter an integer in C++". – Kerrek SB Sep 11 '13 at 11:44
  • Why is there always an idiot putting -1 without justification on people's questions? – filipehd Sep 11 '13 at 11:48
  • There's already a justification, see jrok's comment. Question does not meet the standards, in particular because it misses both code examples. – MSalters Sep 11 '13 at 13:19

2 Answers2

2

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.

jrok
  • 54,456
  • 9
  • 109
  • 141
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Alternative for repeating: `std::all_of`, `std::any_of`, or `std::none_of`. E.g. `if (std::all_of(input.begin(), input.end(), &::isdigit)) { }`. – MSalters Sep 11 '13 at 13:21
0

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.

Kolyunya
  • 5,973
  • 7
  • 46
  • 81