Structures Program not working as intended (Bug)

Viewed 52

I have been working on reading data from a file, which contains student name and age in the format:

John

12

Jane

13

Julia

18

Here's the program I wrote:

  #include <stdio.h>
    #include <stdlib.h>
    struct record{
        char name[50];
        int age;
    };
    int main(){
        FILE *fp;
        fp=fopen("sample2.txt","r");
        struct record a[50];
        int counter=1;
        int i=0;
        while (!EOF){
        if (counter%2!=0){
            fgets(a[i].name,50,fp);
            counter++;
        }
        if (counter%2==0){
            a[i].age=getw(fp);
            counter++;
            i++;
        }
    }
    return 0;
    }

However, on printing a[0].name, I am not getting expected output. Can someone help?

1 Answers

As already pointed out in the comments, EOF is a value defined in stdio.h and does not say anything about your file descriptor. I also would recommend you to use fscanf (As long you are sure that the names in the file are all of the correct length). fscanf takes a string similar to printf, specifying the elements you are expecting and returns the number of possible matches. Also it helps you with converting your data to the correct datatypes. So the code could look like this:

#include <stdio.h>
#include <stdlib.h>
struct record
{
  char name[50];
  int age;
};

int main ()
{
  FILE *fp;
  fp = fopen ("sample2.txt", "r");
  struct record a[50];
  int i = 0;
  while (fscanf(fp, "%s\n%d\n", (char *) a[i].name, &a[i].age) > 0) {
    i++;
  }
  printf("%s %d\n", a[1].name, a[1].age);
  return 0;
} 
Related