I'm reading input into a std::string and need to determine whether it contains a digit or another character. The input should represent a playlist choice from 1 through 4. What is the proper C++ way to validate the characters before converting the string with stoi, and how should I reject values outside that range?
3 Answers
A digit character has a consecutive character-code range, but you generally should not hard-code ASCII values for this. std::isdigit is clearer and more portable. Also, checking whether the input is numeric is separate from checking its allowed value: an input like "9" contains only digits, but it should still be rejected if the valid choices are only 1 through 4.
You can test a single character with std::isdigit(c). If you want to check the whole input manually, loop through the string and reject it as soon as one character is not a digit. Make sure to include , and pass the character as unsigned char when using the cctype functions.
Include and use std::isdigit while checking every character in the string. Because the input is a string, validate it before calling stoi. For example: bool allDigits = !userinput.empty() && std::all_of(userinput.begin(), userinput.end(), [](unsigned char c) { return std::isdigit(c); }); Then check allDigits and, if it is true, convert the value and verify that it is between 1 and 4.

That makes sense—the input needs both checks: first confirm every character is a digit, then convert it and verify that the resulting number is in the valid range.