Search code examples
c++ccountdigits

How can I count the number of digits in a number up to 1000 digits in C/C++


How can I count the number of digits in a number up to 1000 digits in C or C++

#include <stdio.h>

int main()
{
    int num,counter=0;

    scanf("%d",&num);

    while(num!=0){
        num/=10;
        counter++;
    }

    printf("%d\n",counter);
}

This code works just for numbers up to 10 digits — I don't know why.


Solution

  • Since most computers can't hold an integer that is 1000 digits, you will either have to operate on the input as a string or use a Big Number library. Let's try the former.

    When treating the input as a string, each digit is a character in the range of '0' to '9', inclusive.

    So, this boils down to counting characters:

    std::string text;
    cin >> text;
    const unsigned int length = text.size();
    unsigned int digit_count = 0;
    for (i = 0; i < length; ++i)
    {
      if (!std::isdigit(text[i]))
      {
        break;
      }
      ++digit_count;
    }
    cout << "text has " << digit_count << "digits\n";