I want to know how many times a number appears in a string read from a file, but I'm not able to solve my problem.
Here is my C code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int MAX_MEM = 100000, i, count=0;
char string[MAX_MEM];
char search[MAX_MEM];
FILE *fp;
fp = fopen("prova1000.txt", "r");
if (fp != NULL) {
while (!feof(fp)){
fread(string, sizeof(string), MAX_MEM, fp);
printf("%s",string);
char search[MAX_MEM];
printf("\nEnter the number to search:");
gets(search);
char *equal = strstr(string,search);
if(equal!= NULL){
printf("The number introduced is in the list\n");
while(equal!=NULL){
count++;
printf("The number is %d times\n", count);
}
}
else{
printf("The number introduced is not in the list\n");
}
}
}
else
printf("Couldn't open the file");
return 0;
fclose(fp);
}
The prova1000.txt
is something like this:
100000000000000
100000000000001
100000000000001
100000000000003
100000000000004
100000000000005
100000000000006
100000000000007
100000000000008
...
For example, I would want to show in count that 100000000000001
appears twice. How can I do that?