我有一个以这种方式格式化的txt文件:
MyDepartureTown MyDestinationTown 123.45 Vehicle 12
我正在尝试将数据导入到我的C程序中。这是我用来实现的代码:
void import_city_info(Grafo *G)
{
char city_dep[20];
char city_des[20];
double km;
char vehicle[12];
int time;
FILE *data_file = fopen("data/routes.txt", "r");
if (data_file == NULL)
{
fprintf(stderr, "Errore. Impossibile aprire il file.\n");
exit(EXIT_FAILURE);
}
while (5 == fscanf(data_file, "%s %s %f %s %d", &city_dep, &city_des, &km, &vehicle, &time))
{
printf("%2.3f\n", km);
//more code...
}
}
当我尝试打印出双号时,它会输出0.00
。它实际上正确导入了除double之外的所有数据。我做错了什么?
答案 0 :(得分:1)
您使用错误的说明符来阅读double
。这将调用未定义的行为。您需要%lf
。
while (5 == fscanf(data_file, "%s %s %lf %s %d", &city_dep, &city_des, &km, &vehicle, &time))
{