How can I check whether user input contains digits in C++?

0
0
Asked By MellowPine42 On

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

Answered By SilverKite58 On

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.

Answered By CobaltWren7 On

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.

MellowPine42 -

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

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.