# c++ how to check each digit in an integer and compare it to the base number

1965 views
7

so basically, I am having trouble figuring out how to separate each digit in an integer number. Basically, I had to ask the user what the base number was, and then ask them for two integer numbers. Now, I have the task of checking to make sure each digit in the two integers are smaller than the base number (I have no idea how to do this!).

An example would be something like this: Enter a base: 3 Enter your first number: 00120 Enter your second number: 11230

So basically I would have to check each digit in the first and second number. Where the first number would be valid because all digits are smaller than 3, and the second number would be invalid because it has a 3 in it which is not smaller than the base.

I've spent multiple hours trying to figure this out on my own and have had no luck.. Any help would be fully appreciated.

You may find the modulo operator, `%` helpful.

Near duplicate: C++ get each digit in int. Ignore the chosen answer. While it does work, the brutal inefficiency of it has earned the downvotes it has received. Focus on the later answers.

7

If you're asking for user input, you don't yet have any integers. You have text, and all you need to do is check whether the text contains valid digit characters. As long as you don't get into bases greater than 10, that's simple, because the characters `'0' ..'9'` are required to be contiguous and increasing, so you can convert a digit character to its numerical value by subtracting `'0'` from it.

``````bool is_valid(char ch, int base) {
return isdigit(ch) && ch - '0' < base;
}
``````

posted this