简体   繁体   中英

How to count the occurrence of every digit in a given input?

Hi im trying to write a program that can read a line and counts the occurrence of every digit (eg a2bc8c45v28 should gives 0020110020). I came up with the following program:

int main() {
int t;
int count[10]={};
while(scanf("%*c%1d", &t)==1){
    printf("%d\n",t);
    count[t]++;
}
for(int i=0;i<10;i++) printf("%d ",count[i]);
return 0;

}

However this gives an incorrect output it skips some digits. Can anybody explain why this is happening?

scanf is absolutely the wrong tool for this. To explain what is happening, you just need to walk through it and understand the format string. ("Understand the format string", unfortunately, is the root cause of 99% of scanf confusion.)

The format string "%*c%1d" will match (and discard) one byte. If the second byte is a digit it will match. On the input a2 , scanf will return 1 and leave the file pointer at the character after the 2. If the next inputs are bc as in the sample input, scanf will return 0 (since c is not a digit) and your loop terminates.

Just stop using scanf and use fgetc instead.

  1. I would say that there is the issue in the logic of the program. At its simplest, it should be as follows
  • Step 1: Input a string

  • Step 2: Process the string (count occurrences of digits)

  • Step 3: Output the result

    At the moment Step 1 and Step 2 are messed up together, and it makes things problematic.

  1. If you need to process a string, you need to create it first, and you are not doing this in your code.
#include <stdio.h>

int main() {
char s[100];
int count[10]={0};

// Input string
printf("Input a string: ");
scanf("%s", s);

// Process string and count digits
for (int i=0; s[i] != '\0'; i++) {
    if ( s[i]>='0' && s[i]<='9' ) {
        count[ s[i]-48 ]++;
    }
}

// Output the result
for(int i=0;i<10;i++) printf("%d ",count[i]);

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM