Get the number of digits in an int
You can use stringstream
for this as shown below
stringstream ss;
int i = 234567545;
ss << i;
cout << ss.str().size() << endl;
How about division:
int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;
or use the log10
method from <math.h>
.
Note that log10
returns a double
, so you'll have to adjust the result.
Nobody seems to have mentioned converting it to a string, and then getting the length. Not the most performant, but it definitely does it in one line of code :)
int num = -123456;
int len = to_string(abs(num)).length();
cout << "LENGTH of " << num << " is " << len << endl;
// prints "LENGTH of 123456 is 6"
Make a function :
int count_numbers ( int num) {
int count =0;
while (num !=0) {
count++;
num/=10;
}
return count;
}