Count number (0-9) occurrences in a string from a txt file in C
I created the part that reads the string from the file and saves it as the variable "line"
My idea is to create a table with 10 elements that at the beginning are 0 and for example if I found 2 numbers of 0 it changes the table[1] in 2 or if it founds 1 number of 9 it changes table[10] to 1 but couldn't implement it
Output of the string "456 890 111111" should be:
Number 1 appears 6 times
Number 1 appears 1 times
...
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
int table[10];
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
fclose(f);
return 0;
}
Updated code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
unsigned int table[10] = { 0 };
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
int n=0;
for ( char *p = line; *p != '\0'; p++ )
{
if ( '0' <= *p && *p <= '9' ) {
++table[*p - '0'];
}
}
fclose(f);
for (int i=0; table[i] < 10; i++) {
printf("Number", i, "apears", table[i], "times");
}
return 0;
}