#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
int word;
int num,num2;
int numcount1=0,numcount2=0;
printf("Please enter a keys: ");
if (scanf("%d %d", &num, &num2)==2 ){
} else {
printf("Error:Must two integers");
}
file=fopen("data.txt","r");
while ((word=fgetc(file))!=EOF){
fprintf(stdout, "%c",word);
if (word == num) numcount1++;
if (word == num2) numcount2++;
}
printf("'%d' is found %d times in the txt file\n",num,numcount1);
printf("'%d' is found %d times in the txt file\n",num2,numcount2);
fclose(file);
return 0;
}
数据.txt
1 5 30
9 8 77
3 1 15
2 3 8
我要输出
[1111@11111 ~]$ ./count
Please enter a keys: 1 2
'1' is found 2 times in txt file
'2' is found 1 times in txt file
我的问题是输入“1”无法计数。 我尝试测试 (word == '1') numcount 可以计数,但也可以计数 '15' 整数,总共 3 次也不是 2 次
谢谢!
最佳答案
while (fscanf(file, "%d", &word)!=EOF){
if (word == num) numcount1++;
if (word == num2) numcount2++;
}
关于统计用户输入的整数与C程序中文本文件的匹配情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26364265/