user1417815 user1417815 - 4 years ago 97
C Question

Get the number of digits in an int

How to detect the length of an integer? in case i had le: int test(234567545);

how do i know how long the int is? like telling me there is 9 numbers inside it???

i have tried :

char buffer_length[100];

// assign directly to a string.

sprintf(buffer_length, "%d\n", 234567545);

string sf = buffer_length;

cout <<sf.length()-1 << endl;

but there most be a simpler way of doing it or more clean...

Answer Source

How about division:

int length = 1;
int x = 234567545;
while ( x /= 10 )

or use the log10 method from <math.h>.

Note that log10 returns a double, so you'll have to adjust the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download