【发布时间】:2016-04-06 18:51:54
【问题描述】:
struct athlete{
char firstName[50];
char lastName[70];
int age, total, bronze, gold, silver, year;
char country[70];
char sport[100];
};
我有一个结构来存储来自给定文件的奥运会运动员姓名奖牌国家年龄等。 A. J. Mleczko 26 美国 2002 冰球 0 1 0 1
Aaron Armstrong 30 Trinidad and Tobago 2008 Athletics 0 1 0 1
Aaron Egbele 25 Nigeria 2004 Athletics 0 0 1 1
Aaron Gate 21 New Zealand 2012 Cycling 0 0 1 1
所以我在做的是这样的:
void readFile(){
FILE *fptr;
int i;
fptr = fopen("olympics.txt", "r");
if (fptr == NULL)
{
printf ("Error");
}
i = 0;
while (!feof(fptr))
{
fscanf(fptr,"%s %s %d %s %d %s %d %d %d %d ", athletes[i].firstName,athletes[i].lastName, &athletes[i].age, athletes[i].country, &athletes[i].year, athletes[i].sport, &athletes[i].gold, &athletes[i].silver, &athletes[i].bronze, &athletes[i].total);
i++;
}
}
每次我运行它,程序都会崩溃。我也在尝试运行一个简单的搜索,所以这可能是个问题。
void compareString(char first[], char second[]) {
int i = 0;
struct athlete athletes[2000];
for(i = 0; i < 2000; i++)
{
if(strcmp(athletes[i].firstName, first) == 0 && strcmp(athletes[i].lastName, second) == 0 )
{
printf("%s%s", athletes[i].firstName, athletes[i].lastName);
}
else
{
printf("error");
}
}
}
【问题讨论】:
-
New Zealand等不是单个字符串。因此,您的格式说明符不同步。 -
哦,我明白了,谢谢 :D
-
请注意,“程序只是崩溃”是没有用的。什么时候,用什么信息,等等等等会有帮助。此外,如果您在调试器中单步执行,这个问题的答案将很明显
-
如果文件
"olympics.txt"打不开,你认为会发生什么? -
你使用调试器了吗?
标签: c file data-structures