C 程序 - 验证从文本文件中读取的数字

C Program - Validate numbers read from a text file

我正在从一个文本文件中读取 15 个数字,每个数字在一个新行中:

1
2
3
4
5
10
12
13
14
15
21
22
23
24
26

正如您从代码中看到的那样,我需要验证数字以便它们小于 26,否则终止程序。

目前我只是在将它插入数组 (numArray) 后才进行验证。有没有更简洁的方法(在插入数组之前进行验证)?

问题是,我似乎无法获取正在读取的文本文件中的实际 。这就是为什么我使用数组上的循环索引验证它 (int x = numArray[i];).

感谢任何帮助,我对 C 编程还很陌生。谢谢

FILE *myFile = fopen(dataset.txt, "r");
int numArray[15];

if (myFile != NULL) {

    for (int i = 0; i < sizeof(numArray); i++)
    {
        //insert int to array
        fscanf(myFile, "%d", &numArray[i]);

        //Validate number
        int x = numArray[i]; 
        if (x > 25) {
            printf("Invalid number found, closing application...");
            exit(0);
        }
    }

    //close file
    fclose(myFile); 
}
else {
    //Error opening file
    printf("File cannot be opened!");
}

当然你可以把它存储在局部变量中,只有在有效时才赋值。但是由于您正在调用 exit(0) 如果无效,它不会改变任何东西。我想你想从循环中 break 代替。

顺便说一句,你的循环是错误的。你必须将 sizeof(numArray) 除以一个元素的大小,否则你会循环太多次,如果输入文件中的数字太多,你会崩溃机器(是的,我还添加了一个结束测试-文件)

if (myFile != NULL) {

    for (int i = 0; i < sizeof(numArray)/sizeof(numArray[0]); i++)
    {
        int x; 
        //insert int to array
        if (fscanf(myFile, "%d", &x)==0)
        {
            printf("Invalid number found / end of file, closing application...\n");
            exit(0);  // end of file / not a number: stop
        }

        //Validate number
        if (x > 25) {
            printf("Invalid number found, closing application...\n");
            exit(0);
        }
        numArray[i] = x;
    }

    //close file
    fclose(myFile); 
}