20

How do I 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 must be a simpler way of doing it or more clean...

user1417815
  • 425
  • 2
  • 7
  • 16
  • 6
    Just a thought: How should negative numbers be handled? – Joey Jun 22 '12 at 07:32
  • 2
    Why do you need `std::string` here? You could just do a `strlen(buffer_length)`. You also don't need the `\n` and thus no `-1`. – leemes Jun 26 '12 at 23:22
  • Possible duplicate of : http://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer – Rishi Feb 06 '17 at 09:18
  • 3
    C and C++ are different programming languages. A number does not have digits, only its decimal representation has digits. – Basile Starynkevitch Feb 26 '17 at 10:13

9 Answers9

38

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.

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
10

Make a function :

int count_numbers ( int num) {
   int count =0;
   while (num !=0) {   
      count++;  
      num/=10;
   } 
   return count;
}
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
Shehzad Bilal
  • 2,455
  • 2
  • 17
  • 27
9

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"
jmg
  • 537
  • 7
  • 12
5

You can use stringstream for this as shown below

stringstream ss;
int i = 234567545;
ss << i;
cout << ss.str().size() << endl;
Sanish Gopalakrishnan
  • 1,649
  • 1
  • 12
  • 21
4

if "i" is the integer, then

int len ;

char buf[33] ;

itoa (i, buf, 10) ; // or maybe 16 if you want base-16 ?

len = strlen(buf) ;

if(i < 0)
    len-- ;    // maybe if you don't want to include "-" in length ?
Thorsen
  • 403
  • 4
  • 10
4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    int i=2384995;
    char buf[100];

    itoa(i, buf, 10); // 10 is the base decimal

    printf("Lenght: %d\n", strlen(buf));


    return 0;
}

Beware that itoa is not a standard function, even if it is supported by many compilers.

A_nto2
  • 1,076
  • 7
  • 16
2

len=1+floor(log10(n));//c++ code lib (cmath)

congar
  • 201
  • 2
  • 8
1

looking across the internet it's common to make the mistake of initializing the counter variable to 0 and then entering a pre-condition loop testing for as long as the count does not equal 0. a do-while loop is perfect to avoid this.

    unsigned udc(unsigned u) //unsigned digit count
    {
      unsigned c = 0;
      do
        ++c;
      while ((u /= 10) != 0);
      return c;
    }

it's probably cheaper to test whether u is less than 10 to avoid the uneccessary division, increment, and cmp instructions for cases where u < 10.

but while on that subject, optimization, you could simply test u against constant powers of ten.

    unsigned udc(unsigned u) //unsigned digit count
    {
      if (u < 10)   return 1;
      if (u < 100)  return 2;
      if (u < 1000) return 3;
      //...
      return 0; //number was not supported
    }

which saves you 3 instructions per digit, but is less adaptable for different radixes inaddition to being not as attractive, and tedious to write by hand, in which case you'd rather write a routine to write the routine before inserting it into your program. because C only supports very finite numbers, 64bit,32bit,16bit,8bit, you could simply limit yourself to the maximum when generating the routine to benefit all sizes.

to account for negative numbers, you'd simply negate u if u < 0 before counting the number of digits. of course first making the routine support signed numbers.

if you know that u < 1000, it's probably easier to just write, instead of writing the routine.

   if (u > 99) len = 3;
   else
   if (u > 9)  len = 2;
   else        len = 1;
Anonymous
  • 11
  • 2
-1

Assuming nonnegative integer inputs:

#include <iostream>
#include <limits>

using std::cout;

uint64_t digits(uint64_t i) { return i < 10 ? 1 : 1 + digits(i / 10); }
uint64_t powi(uint64_t b, uint64_t e) { return !e ? 1 : b * powi(b, e - 1); }

int main () {
    constexpr uint64_t max = std::numeric_limits<uint64_t>::max();
    const     uint64_t k = digits(max);
    const     uint64_t l = k - 1;
    const     uint64_t X = 10;
    uint64_t i, n = 0;
    for (i = 0; i < k; i++) {
        cout << n << " has " << digits(n) << " digits." << '\n';
        n = i<l ? powi(X, i + 1) - 1 : max;
        cout << n << " has " << digits(n) << " digits." << '\n';
        n = X * powi(X, i);
    }
    return 0;
}
q-l-p
  • 3,680
  • 3
  • 14
  • 33