Error when reading txt file, can’t read txt file correctly

here is the correct code

#include"stdio.h"
#include"stdlib.h"
#include"string.h"
void delete_n(char a[]){
    size_t x=strlen(a);
        if(a[strlen(a)-1]=='\n'){
            a[strlen(a)-1]='\0';
        }
}
struct age{
    char id[10];
    char name[50];
    int numb;
    int score;
};
int main(){
    age dnu[20];
    char x[50];
    char xx[50];
    int d;
    int n;
    FILE *f;
    f = fopen("ex3","r");
    if(f==NULL){
        printf("Error");
        exit(0);
    }
//  if( fgets(x,60,f)!=NULL){
//      puts(x);
//  }
    
    if(fgets(x,50,f)!=NULL){
//          printf("%s",x);
        }
    n=atoi(x);
//  printf("===%d===",n);
    for(int i=0;i<n;i++){
        if(fgets(dnu[i].id,10,f)!=NULL){
//          printf("%s",dnu[i].id);
        }
        if(fgets(dnu[i].name,50,f)!=NULL){
//          printf("%s",dnu[i].name);
        }
//      fscanf(f," %[^\n]s ",&dnu[i].name);
        
        if(fgets(x,50,f)!=NULL){
//          printf("%s",x);
        }
        dnu[i].numb=atoi(x);
        if(fgets(xx,50,f)!=NULL){
//          printf("%s",xx);
        }
        dnu[i].score=atoi(xx);
    }
//  printf("===%s==",x);
    printf("%10s    %20s    %20s    %20s","majors","Name majors","number of students ","matriculation score\n");
    for(int i=0;i<n;i++){
        delete_n(dnu[i].id);
        delete_n(dnu[i].name);
        printf("%10s    %20s    %20d    %20d",dnu[i].id,dnu[i].name,dnu[i].numb,dnu[i].score);
        printf("\n");
    }
    fclose(f);
}

sorry for my english
ok, the questioner’s code doesn’t run properly because the program that reads the file defaults to a string, so you need to use a script to convert the string to an integer variable atoi(x1 ,x2)

Leave a Comment