统计用户输入的整数与C程序中文本文件的匹配情况

标签 c text fopen

#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/

相关文章:

c++ - Linux下USB Missile Launcher编程

html - 自定义删除线 CSS

html - 将文本输入框对齐到 div 的右侧

c - 在c中逐行从文件中读取值

c - 如果在同一执行中写入和读取文件,程序将挂起

C stat() 忽略文件

c++ - 为什么我可以在另一个函数中定义一个函数?

algorithm - 最佳聚类算法? (简单解释)

c++ - 在C/C++中使用stdio文件操作时如何检测磁盘空间不足?

c - 如何检查dlsym中函数指针的返回值?