简体   繁体   English

无法正确将双数导入C程序

[英]Can't correctly import double numbers into C program

I have a txt file formatted this way: 我有一个这样格式化的txt文件:

MyDepartureTown MyDestinationTown 123.45 Vehicle 12

I am trying to import the data into my C program. 我正在尝试将数据导入到我的C程序中。 Here it is the code I am using to acheive just that: 这是我用来实现以下目的的代码:

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...

    }
}

As I try to print out the double numbers, it outputs 0.00 . 当我尝试打印双精度数字时,它输出0.00 It's actually importing correctly all the data except the double. 实际上,它正确地导入了除double以外的所有数据。 What am I doing wrong? 我究竟做错了什么?

You are using a wrong specifier to read double . 您使用了错误的说明符来读取double This will invoke undefined behavior. 这将调用未定义的行为。 You need %lf . 您需要%lf

while (5 == fscanf(data_file, "%s %s %lf %s %d", &city_dep, &city_des, &km, &vehicle, &time))
{

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM