【问题标题】:File contents wont read into structure文件内容不会读入结构
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 谢谢。 [^0-9] 有什么作用?
  • @C.Red 这匹配除 '0', '1', '2', ... , '9' 以外的所有字符
猜你喜欢
  • 2023-01-12
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多