以下是我想要了解的程序.我感到困惑的唯一部分是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)
fscanf
返回已读取的字段数.格式字符串"%s %s %s %i"
有四个字段,所以while (fscan(...) == 4)
循环只要fscanf
能够读取所有四个字段.如果它到达文件结尾(EOF),或者文件包含格式不正确的数据(例如,该%i
字段不是有效整数),它将退出.
strcmp
如果两个字符串匹配则返回0.if (strcmp(a, b) == 0)
是检查C中两个字符串是否相等的最常用方法.