我需要从C程序中的data.txt
文件导入一些数据。我的数据来源是这样的:
A ABC001 B
A ABC002 B
A ABC003 C
B ABC004 C
B ABC005 E
C ABC006 B
D ABC007 A
D ABC008 B
E ABC009 D
我已定义了一种新数据类型来保存所有信息:
typedef struct node {
char street_name;
char number_plate[7];
char destination;
} Car;
这是我尝试将上述文件中的数据导入数组:
int main(void)
{
FILE *file;
int i = 0;
Car carinfo[9];
file = fopen("data.txt", "r");
while (EOF != fscanf(file, "%c %6s %c", &carinfo[i].street_name,
&carinfo[i].number_plate,
&carinfo[i].destination))
{
printf("Loop #%d\n", i+1);
i++;
}
for (i = 0; i < 9; i++)
{
printf("Street Name: %c, Number Plate: %s, Destination: %c\n", carinfo[i].street_name,
carinfo[i].number_plate,
carinfo[i].destination);
}
fclose(file);
return 0;
}
while
循环正在执行10次,然后使程序崩溃,因为显然它忽略了应该阻止另一次迭代的EOS
。
我在这里做错了什么?有人可以帮我解决一下吗?
答案 0 :(得分:2)
请更改
while (EOF != fscanf(file, "%c %6s %c", &carinfo[i].street_name,
到
while (3 == fscanf(file, " %c %6s %c", &carinfo[i].street_name,
再试一次。
输入文件中的每一行都有一个换行符,应该忽略它,第一个%c
之前的空格就会这样做。