[英]C, how to use fgets and fscanf together
i hav a homework form univ. 我有一份家庭作业表格。 that is use file IO. 即使用文件IO。
there is like this TXT file: 像这样的TXT文件:
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. 我必须阅读此文件并保存到struct中的var中。 and prof. 和教授。 said to me. 对我说。 I have to use fgets and fscanf together. 我必须一起使用fgets和fscanf。 if I use only fscanf its not working nicely because "Alex Fernandes" has space in it. 如果我仅使用fscanf,则其效果不佳,因为“ Alex Fernandes”中有空间。
but even though I use fgets and fscanf together, its not working.. so i need help u. 但是即使我同时使用fgets和fscanf,它也不起作用..所以我需要帮助。
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;
}
只需在fscanf()
参数的末尾添加一个空格即可使用换行符。
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.