How can I check whether user input contains digits in C++?
Asked by
witty remark pending
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?
Answers
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.
Reply to this answer
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.
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
witty remark pending: That makes senseโIโll validate the string first and only convert it after confirming that every character is a digit.