Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

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

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++

question from:https://stackoverflow.com/questions/65872694/how-to-find-the-number-of-digits-int-digits-in-c-upto-100-or-1000-digits

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
    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);
    }
    return 0; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...