How many digits are in a number?

This might sound like a simple question, but I can't think of a reasonable answer. Suppose you make a program where a user must input an ID number, and the ID number must be exactly seven digits, how would you write a function that could count the amount of digits in a number input by the user? The only way I've been able to think of is to make an if statement that says if(user_number < 999,999 || user_number > 10,000,000), but that seems unreasonable. I can't think of a way to do it with an array, because you wouldn't ask the user to input an ID one digit at a time, so the numbers couldn't be stored individually in an array. Is there some type of mathematical expression that can solve how many digits are in a number?
floor(log(abs(n))/log(radix)) + 1
Works for integers, at least.

I would go with your first solution. It's dead simple.
Last edited on
Your way seems simplest to me.
another way would be count the 0-9's
another way would be check the string size, but that will not catch alpha chars.

closed account (48T7M4Gy)
Your way seems simplest to me too. Add a few other checks as below and decimal numbers, leading zeroes and non integer characters get captured as errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    int ID = 0;
    
    while ( std::cout << "Please enter  ID: " and (!(std::cin >> ID) or ID > 10000000 or ID < 999999 ))
    {
        std::cout << "Wrong!\n";
        std::cin.clear();
        std::cin.ignore(1000, '\n');
    }
    std::cout << ID << '\n';
    return 0;
}
Last edited on
Yea, what they said... if you handle the garbage and don't allow leading zeros, the comparison is the easy, simple answer.


Last edited on
Topic archived. No new replies allowed.