cstringdigitsatoi

Digit Frequency calculating code in C not working


So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.

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

int main() {
    // takes string input
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    //turns the string to int
    int x = atoi(s);
    int temp = x, len = 0;
    //calculates string length
    while (x != 0) {
        x = x / 10;
        len++;
    }
    x = temp;
    //parses through the string and matches digits with each number
    for (int j = 0; j < 10; j++){
        int count = 0;
        for(int i = 0; i < len; i++){
            if(x % 10 == j){
                count++;
            }
            x = x / 10;
        }
        x = temp;
        printf("%d ", count);
    }
    return 0;
}

Solution

  • To write a correct and reasonable digit-counting program: