【问题标题】:C: issues with fscanf (repetitive output)C:fscanf 的问题(重复输出)
【发布时间】:2021-10-11 05:28:53
【问题描述】:

我是 C 编程的新手。我尝试了以下代码,它将简单地从名为 "student_data.txt" 的文件中打印控制台中的信息。代码在这里:

#include <stdio.h>

int main()
{
    FILE* fp;

    fp = fopen("student_data.txt", "r");
    if (!fp)
    {
        perror("Error: ");
        return 1;
    }

    /*
    The file is this:
    id 1
    name abc
    total_gpa 9.55
    hsc 4.55
    ssc 5.0

    id 2
    name def
    total_gpa 9.55
    hsc 5.0
    ssc 4.55

    id 3
    name xyz
    total_gpa 8.00
    Alevel 4.0
    Olevel 4.0

    id 4
    name pqr
    total_gpa 10
    hsc 5.0
    ssc 5.0

    id 5
    name ali
    total_gpa 9.67
    hsc 4.67
    ssc 5.0

    id 6
    name hasan
    total_gpa 7.5
    Alevel 3.5
    Olevel 4.0

    id 7
    name kamal
    total_gpa 7.5
    Alevel 4.0
    Olevel 3.5
    
    */

    char input[10][30];

    while(!feof(fp))
    {
        for(int i = 0; i < 10; i++)
        {
            fscanf(fp, "%s", input[i]);
        }

        for(int i = 0; i < 10; i++)
        {
            printf("%s ", input[i]);
            if(i % 2 == 1)
            {
                printf("\n");
            }
        }
        printf("\n");
    }

    fclose(fp);
}

当我运行代码时,输​​出显示 id 7 的信息两次。我不知道如何解决这个问题。 while循环有什么问题吗?

.....

id 7
name kamal
total_gpa 7.5
Alevel 4.0
Olevel 3.5

id 7
name kamal
total_gpa 7.5
Alevel 4.0
Olevel 3.5

提前致谢。

【问题讨论】:

    标签: c file scanf


    【解决方案1】:

    fscanf 返回它可以找到的匹配数量,在您的情况下始终必须为 1,这意味着如果它不是 1,您可以停止。

    这应该可以解决它:

    #include <stdbool.h>
    #include <stdio.h>
    
    int main()
    {
        FILE* fp;
    
        fp = fopen("student_data.txt", "r");
        if (!fp)
        {
            perror("Error: ");
            return 1;
        }
    
        char input[10][30];
    
        while(1)
        {
            bool end = false;
            for(int i = 0; i < 10; i++)
            {
                if (fscanf(fp, "%s", input[i]) != 1){
                    end = true;
                }
            }
    
            if (end) break;
    
            for(int i = 0; i < 10; i++)
            {
                printf("%s ", input[i]);
                if(i % 2 == 1)
                {
                    printf("\n");
                }
            }
            printf("\n");
        }
    
        fclose(fp);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 2015-08-06
      相关资源
      最近更新 更多