#include <stdio.h>
#include <ctype.h>
void task(const char *file_name)
{
FILE *file = fopen("1.txt", "r");
if (file == NULL){
printf("Error opening file.\n");
return;
}
int num;
int min =2147483647 ;
int min_count=0;
while (fscanf(file, "%d", &num) !=isdigit(num)) {
if (num < min) {
min = num;
min_count = 0;
}
if (num == min){
min_count += 1;
}
}
printf("Minimum:%d exists %d time(s) ",min, min_count);
fclose(file);
}
int main()
{
task("numbers.txt");
return 0;
}
所以我有一个打开文件、扫描它的代码,因此我需要获取文件中最小数字的数量 现在,当它遇到非数字字符时,它会崩溃 尽管遇到这些字符,我该如何修改我的程序才能工作?
fscanf
时,返回值指示成功读取了多少个值。您正在寻找 1
来表明您的案例成功。
while (fscanf(file, "%d", &num) == 1) {
if (num < min) {
min = num;
min_count = 0;
}
if (num == min){
min_count += 1;
}
}