【问题标题】:Beginner programer confusion on while statement using fscanf初学者对使用 fscanf 的 while 语句感到困惑
【发布时间】:2014-12-16 19:44:08
【问题描述】:

以下是我试图理解的程序。我唯一感到困惑的部分是 while fscanf(....) == 4 的 while 语句以及 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;
 }

【问题讨论】:

  • 您可能想阅读例如this fscanf reference,看看它返回了什么。还可以在该网站上搜索其他功能 (strcmp) 以获取更多信息。

标签: c file scanf


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    解释

    if(( S[n].age > 40 ) && ( strcmp(S[n].major, "ECE") == 0 ))
        n = n + 1;
    

    表达式的两个部分

    if (condition1 && condition2)
    

    必须是真的。

    如果age &gt; 40,第一部分显然是正确的。

    如果比较的两个字符串相同,则第二部分为真,当strcmp(...) == 0

    fscanf() 的结果已经存储在数组索引[n] 中,但仅当条件为真时索引才会递增。否则结果将被下一条数据线覆盖(如果没有另一条数据线则丢弃)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 2015-07-30
      • 2015-12-01
      相关资源
      最近更新 更多