文件内容不会读入结构

时间:2016-04-06 18:51:55

标签: c file data-structures

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");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

"Trinidad and Tobago""New Zealand"包含空格,可防止%s正确扫描它们。此外,使用while(!feof(fptr))并不是一个好主意。

您可以使用以下循环输入数据:

while (fscanf(fptr," %s %s %d %[^0-9] %d %[^0-9] %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) == 10)
{
    i++;
}