How to return the length of an integer input

Is it possible to get the length of an integer input?


in vb ther is the len function, how about c++?
What function should i use to do this?
You could convert it to a string and get the length of the string.
You could count how many times it is divisible by ten.
There might be better solutions than these though.
thanks dude!!
Off of what syneris said: specifically, you're probably going to want to use itoa & strlen.
It is also possible, which I think takes less CPU work, to check if it is above a certain number. Like this function does:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <math.h>

unsigned int getLength(int number)
{
    unsigned int length = 0;

    if (number < 0) //When it is beneat zero is has a - before the number, so that makes the length larger
        length++;

    number = abs(number); //this is because you need to work with the positive version of it.

    for (unsigned char c = 1; c < 10; c++) //It only goes to 10 since 2^32 is in text 10 symbols long
    {
        if (number < pow(10, c)) //when you reach a point where it is smaller than pow(10, c) you know the length.
            length += c;
            //Like, when it is 987 it is smaller than 1000 but not smaller than 100. So you can see that the zeros of the result of pow(10, c) represents the length of the number. c is the number of zeros so c is added to the length.
    }

    return length;
}

Last edited on
this is the same as the 2nd solution syneris provided...
Yeah, I should read better, but here you have some example code :P
Topic archived. No new replies allowed.