How to find the number of digits int digits in c upto 100 or 1000 digits?

Viewed 239

This is my code:`

#include <stdio.h>
 
void main() {
    int n;
    int count = 0;
    printf("Enter an integer: ");
    scanf("%d", &n);
 
    // iterate until n becomes 0
    // remove last digit from n in each iteration
    // increase count by 1 in each iteration
        
    while (n != 0) {
        n /= 10;     // n = n/10
        ++count;
    }
 
    printf("Number of digits: %lld", count);  
}

I am able to run the code finely but when I enter 15 or 16 digits of number as input then it always shows me that the number of digits is 10. And another problem with this code is that suppose if I input 000 then I want the output to be 3 digits but this code is not able to do that as the condition in the while loop becomes instantly false. So how write a code that enables me to take upto 100 or 1000 digits as input and also enables me to input 0s as well.

Note: This program should be solved using a loop and in C language I found a answer to the question here in stackoverflow written in c++ that I couldn't even understand as I am a beginner and I am learning C. Link to the answer: How can I count the number of digits in a number up to 1000 digits in C/C++

3 Answers

You are taking int variable and you are trying to count a number like whose digit is 100 or 1000. it will not fit with int. so take input as a string and count the length of string.

Instead of reading a number, read a string and count the digits:

#include <stdio.h>

int main() {
    char buffer[10000];
    int n;

    printf("Enter an integer: ");
    if (scanf("%9999s", buffer) == 1) {
        for (n = 0; buffer[n] >= '0' && buffer[n] <= '9'; n++)
            continue;
        printf("Number of digits: %d\n", n);
    }
    return 0; 
}

You can also use the scanf() scanset feature to perform the test in one step:

#include <stdio.h>

int main() {
    char buffer[10000];
    int n;

    printf("Enter an integer: ");
    if (scanf("%9999[0-9]%n", buffer, &n) == 1) {
        printf("Number of digits: %d\n", n);
    }
    return 0; 
}

32 bits signed integer has the max value equals 2,147,483,647 so, if you input a bigger one, it will not be stored. I'd make it receiving a string and get its length, like so:

#include <stdio.h>
#include <string.h>

int len = strlen("123123123123132");

Related