C, how to use fgets and fscanf together

2019-02-20 17:39发布

问题:

i hav a homework form univ. that is use file IO.

there is like this TXT file:

Brian
s213551 50 70 70 50
Alex Fernandes
s210011 70 81 50 89
Young Lee
s211213 60 80 60 90
... and more

I have to read this file and save to var in struct. and prof. said to me. I have to use fgets and fscanf together. if I use only fscanf its not working nicely because "Alex Fernandes" has space in it.

but even though I use fgets and fscanf together, its not working.. so i need help u.

this is my source:

#include <stdio.h>
#include <stdlib.h>

typedef struct sMember{
        char name[10];
        char id[10];
        int score[4];
        double avg;
        char grade;
}MEM;

int main(int argc, char *argv[])
{
  MEM member[50];
  FILE *f;
  char fileName[10];
  char s[512];
  int i;
  printf("File Name : ");
  scanf("%s", fileName);
  fflush(stdin);

  i=0;
  if((f = fopen(fileName, "r")) != NULL )
  {

//        while(!feof(f)) 
          while(fgets(member[i].name, sizeof(member[i].name), f) != 0)
        {
         fscanf(f, "%s %d %d %d %d", member[i].id, &member[i].score[0], &member[i].score[1], &member[i].score[2], &member[i].score[3]);

         printf("%s %s %d %d %d %d\n", member[i].name, member[i].id, member[i].score[0], member[i].score[1], member[i].score[2], member[i].score[3]);
         //printf("t: %s\n", member[i].name);
         i++;               
        }
  } 
  else 
  {
      printf("File is Not Exist.\n"); 
  }


  fclose(f);
  system("PAUSE");  
  return 0;
}

回答1:

Just add a space in the end of fscanf() parameter to consume the newline character.

fscanf(f, "%s %d %d %d %d ", member[i].id, &member[i].score[0], &member[i].score[1], &member[i].score[2], &member[i].score[3]);