Yes, I saw that but I want to understand how to find the length of an int type.
If we have variable a=123456 I want to understand its length i.e that it is six characters long.
Is there a function for this like the .size() for strings.
#include <iostream>
usingnamespace std;
int intLength( int N )
{
if ( N < 0 ) return 1 + intLength( -N );
elseif ( N < 10 ) return 1;
elsereturn 1 + intLength( N / 10 );
}
int main()
{
int a[] = { 123456, -345, 9, -5, 0 };
for ( int N : a ) cout << "The length of " << N << " is " << intLength( N ) << endl;
}
The length of 123456 is 6
The length of -345 is 4
The length of 9 is 1
The length of -5 is 2
The length of 0 is 1
Hello, can someone one tell me what is the easiest way to find the length of int type?
Thnks but somehow this doesn't work for me for example
1 2
int a=4; //lenhgt=1
cout<<sizeof(a)<<endl; //it displays 4 not 1
It seems that you did not ask what you actually wanted to know.
To us, the "length of int type" means how much memory is allocated for an object of type int. All ints have same length, because every int is int. The int can store 1 or -2147483648 with equal ease. Really big numbers the int cannot store at all.
Your example implies a different question: How many digits does a base 10 representation of an integer value have?
But I realized you would need to add extra code to handle the value 0 (even more if you want to handle negative values). I'm also not comfortable relying on exact values with floating point numbers.
I think goldenchicken's solution is nice for its simplicity.
cout << to_string(a).length() << endl;
If you want something more efficient, but still reliable, you can use integers to calculate the value using a loop, or using recursion as lastchance did.