使用fscanf的while语句初学者编程混淆

Cas*_*sey 0 c file scanf

以下是我想要了解的程序.我感到困惑的唯一部分是while语句while fscanf(....) == 4以及部分if(...) == 0.

有人可以向我解释这条线及其目的吗?

#include <stdio.h>
#include <stdlib.h>


struct str_student {
    char UFID[9];
    char firstname[20];
    char major[10];
    int age;
};


 int main(int argc, char *argv[]) {
     FILE *fStud = fopen("students.dat", "r");
     struct str_student S[11];

    int i, n = 0;
    while( fscanf(fStud, "%s %s %s %i", S[n].UFID, S[n].firstname, S[n].major, &S[n].age) == 4)          
    {    if(( S[n].age > 40 ) && ( strcmp(S[n].major, "ECE") == 0 ))
            n = n + 1;
    }

    printf("\nStudents of the ECE Department who are 41 or more years old:\n");
    for( i=0; i<n; i++ ) {
         printf("%s\n", S[i].UFID);
    }

    return 0;
 }
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

fscanf返回已读取的字段数.格式字符串"%s %s %s %i"有四个字段,所以while (fscan(...) == 4)循环只要fscanf能够读取所有四个字段.如果它到达文件结尾(EOF),或者文件包含格式不正确的数据(例如,该%i字段不是有效整数),它将退出.

strcmp如果两个字符串匹配则返回0.if (strcmp(a, b) == 0)是检查C中两个字符串是否相等的最常用方法.