There is an error in the process of storing the file input/output in the structure after receiving the formatting using fscanf.

Asked 2 years ago, Updated 2 years ago, 44 views

Creating a program that stores and displays the information contained in grads.txt in the structure. I wrote it as below, but there is a semi-fault error or an infinite loop. To be honest, I have no idea how to solve it.

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp1;
    fp1 = fopen("grades.txt","r");
    int i = 0,j;
    typedef struct
    {
        int number;
        int q[4];
        int total;
    } } student;
    student a[101];
    while(feof(fp1) == 0)
    {
        if(i==0) i++;
        else
        {
            student *st = &a[-1];
            fscanf(fp1,"%d %d %d %d %d %d", &st->number, &st->q[0], &st->q[1], &st->q[2], &st->total);
            printf("%d %d %d %d %d %d\n", st->number,st->q[0], st->q[1], st->q[2], st->total);
            i++;
        }
    }
    fclose(fp1);
    return 0;
}

The content of grads.txt.

ID       Q1 Q2 Q3 Q4 Total
20131122 20 14 18 22    74
20132400 16 23 11 19    69 

c

2022-09-22 19:16

1 Answers

#include <stdio.h>
#include <string.h>

int main()
{
    char hollowString[101];
    FILE *fp1;
    fp1 = fopen("grades2.txt","r");
    int i = 0,j;
    typedef struct
    {
        int number;
        int q[4];
        int total;
        char name[10];
    } } student;
    student a[101];
    fgets(hollowString,100,fp1);
    while(fscanf(fp1,"%d %80s %d %d %d %d %d", &a[i].number, &a[i].name ,&a[i].q[0], &a[i].q[1], &a[i].q[2], &a[i].q[3], &a[i].total) == 7 )
    {
        printf("%d %s %d %d %d %d %d \n", a[i].number, a[i].name ,a[i].q[0], a[i].q[1], a[i].q[2], a[i].q[3] ,a[i].total); 
    }
    fclose(fp1);
    return 0;
}

Stackoverflow for answers. Please refer to the link for the explanation.


2022-09-22 19:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.