下面是一个我试图理解的程序。我唯一感到困惑的部分是 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;
}
最佳答案
fscanf
返回读取的字段数。格式字符串 "%s %s %s %i"
有四个字段,所以 while (fscan(...) == 4)
循环只要 fscanf
能够读取所有四个字段。如果遇到文件结尾 (EOF),或者文件包含格式不正确的数据(例如 %i
字段不是有效整数),它将退出。
strcmp
如果两个字符串匹配则返回 0。 if (strcmp(a, b) == 0)
是 C 中检查两个字符串是否相等的最常用方法。
关于c - 初学者对使用 fscanf 的 while 语句感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27512649/