I'm reading the user's choice into a std::string and need to validate it before converting it with std::stoi. The input should be a number, such as 1, 2, 3, or 4, and values outside that range should be rejected. What is the proper C++ way to determine whether the input contains only digits?
2 Answers
A digit character has a numeric character code, but it’s better not to hard-code ASCII ranges in normal C++ code. Use std::isdigit for the general 0–9 check, then compare the converted integer against the allowed range. For example, after validation, reject the value if std::stoi(userinput) is greater than 4 or less than 1.
Include and check every character with std::isdigit. Since the input is a string, validate all of its characters before calling std::stoi. Also cast to unsigned char when calling isdigit to avoid undefined behavior with negative char values.

That makes sense—I’ll validate the string first and only convert it after confirming that every character is a digit.