我想知道一个数字出现在从文件读取的字符串中出现了多少次,但我无法解决我的问题。计算字符串中出现的次数
这里是我的C代码:
#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);
}
的prova1000.txt
是这样的:
100000000000000
100000000000001
100000000000001
100000000000003
100000000000004
100000000000005
100000000000006
100000000000007
100000000000008
...
例如,我希望在100000000000001
出现了两次计数显示。我怎样才能做到这一点?
对于初学者来说,'while(equal!= NULL){'因为'equal'在循环中没有变化,所以有一个无限循环。这就是为什么“短分支”在“长”之前走的最好例子 - 最后浮出来的“无法打开文件”消息简直令人困惑! – John3136
值得你花时间阅读[this](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong),并使用['fgets'](https:/ /linux.die.net/man/3/fgets)而不是'gets' – yano