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?
3 Answers
You can also avoid parsing a string altogether if you only need one numeric choice: read an int and check whether the stream succeeded, then verify that the value is between 1 and 4. If you need to reject inputs such as 12abc or preserve exact text validation, checking the string first is safer.
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.