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

0
23
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?

3 Answers

Answered By QuietMaple19 On

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.

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.