[英]how to read txt file and store in structure array in c
你如何阅读文本并存储在结构数组中?
我使用了while,但是有什么方法可以使用吗??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct names {
char first[20];
char last[20];
};
struct date {
char month[12];
int day, year;
};
struct person {
struct names name;
struct date birthday;
};
/* Converts "January", "February", ..., "December"
into corresponding numbers 1, 2, ..., 12 */
int convert (char *mon) {
static const char *month[] = { "January", "February","March","April","May","June","July","August",
"September","October", "November","December", NULL };
for (int i = 0; month[i] != NULL; i++) {
if (strcmp(month[i], mon) == 0) {
return i + 1;
}
}
return -1;
}
/* argv[1] contains the filename: cast.txt */
main(int argc, char *argv[]) {
struct person cast[20];
int ncast = 0;
FILE *f;
int i;
if (argc < 2) {
fprintf(stderr, "usage: %s filename\n?? argv[0]);
exit(1);
}
if ((f = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "%s: can't open %s\n", argv[0], argv[1]);
exit(1);
}
/* Reads the file contents into cast[] */ << this is where I need help
int i = 0;
while ((fscanf(f, "%s", "%s", "%d", "%d", "%d",
%cast[i].name.last,
%cast[i].name.first,
%cast[i].birthday.month,
%cast[i].birthday.day,
%cast[i].birthday.year)) != EOf) {
i++;
}
fclose(f);
printf("Cast of Captain America: Civil War\n");
printf("==================================\n\n");
printf("Name (Birthday)\n\n");
for (i = 0; i < ncast; i++)
printf("%s, %s (%02d/%02d/%02d)\n",
cast[i].name.last,
cast[i].name.first,
convert(cast[i].birthday.month),
cast[i].birthday.day,
cast[i].birthday.year % 100);
}
here is the text file
Chris Evans June 13, 1981
Robert Downey April 4, 1965
Scarlett Johansson November 22, 1984
Sebastian Stan August 13, 1982
Anthony Mackie September 23, 1978
Don Cheadle November 29, 1964
Jeremy Renner January 7, 1971
Chadwick Boseman November 29, 1976
Paul Bettany May 27, 1971
Elizabeth Olsen February 16, 1989
Paul Rudd April 6, 1969
Emily VanCamp May 12, 1986
Tom Holland June 1, 1996
Daniel Bruhl June 16, 1978
Frank Grillo June 8, 1965
这段代码不够好,但应该给你一些提示。
for (int i = 0; i < 20 && !feof(f); ++i) {
if (fscanf(f, "%s %s %s %d, %d", cast[i].name.last,
cast[i].name.first, cast[i].birthday.month,
&cast[i].birthday.day, &cast[i].birthday.year) != 5) {
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.