Search code examples
cprintfgetchardigit

C program to find total number of digits


I wrote this program to find the total number of digits from a line of text entered by user. I am having error on using getchar(). I can't seem to figure out what am I doing wrong?

#include <stdio.h>

#define MAX_SIZE 100

void main() {
    char c[MAX_SIZE];
    int digit, sum, i;
    digit, i = 0;

    printf("Enter a line of characters>");
    c = getchar();
    while (c[i] != '\n') {
        digit = 0;
        if (c [i] >= '0' && c[i] <= '9') {
            digit++;
        }
    }
    printf("%d\n", digit);
}

I will be adding all the digits I found using sum variable. but I am getting error on getchar() line. HELP??


Solution

  • You can enter a "line of text" without using an array.

    #include <stdio.h>
    #include <ctype.h>
    
    int main(void) {                    // notice this signature
        int c, digits = 0, sum = 0;
        while((c = getchar()) != '\n' && c != EOF) {
            if(isdigit(c)) {
                digits++;
                sum += c - '0';
            }
        }
        printf("%d digits with sum %d\n", digits, sum);
        return 0;
    }
    

    Note that c is of type int. Most of the library's character functions do not use char type.

    Edit: added the sum of the digits.