【问题标题】:Sscanf not reading identical lines the same waySscanf 没有以相同的方式读取相同的行
【发布时间】:2018-05-22 22:06:39
【问题描述】:
#include <stdlib.h>

void printLine(char* line) {
     char lat, lon;
     unsigned int year, month, day;
     float temp, uncertainty, latitude, longitude;
     char country[100], city[100];
     int result;

     result = sscanf(line, "%u-%u-%u,%f,%f,%[^,],%[^,],%f%c,%f%c", &year,
         &month,&day, &temp, &uncertainty, city, country, &latitude, &lat, &longitude, &lon);

     printf("%u-%u-%u,%f,%f,%s,%s,%f%c,%f%c\n", year, month, day, temp, uncertainty,
         city, country, latitude, lat, longitude, lon);

     printf("sscanf read %i variables\n", result);
}
int main() {
    char line[] = "2013-08-01,19.005,3.621,Addis Abeba,Ethiopia,8.84N,38.11E";
    char line2[] = "1816-03-01,27.426,1.793,Bangkok,Thailand,13.66N,99.91E";
    char line3[] = "1743-11-01,3.264,1.665,New York,United States,40.99N,74.56W";

    printLine(line);
    printLine(line2);
    printLine(line3);
}

有些行读取正确,有些行没有读取最后一个字符。我不确定是什么导致了这个错误,我可能会调用某种未定义的行为,但我不确定它是什么。

【问题讨论】:

  • @user3121023 那我该怎么做才能解决这个问题?
  • ...当然,是否一次读取一行的问题与使用与您的经度中的尾随“E”不匹配的输入字段指令的问题是正交的。

标签: c scanf


【解决方案1】:

正如 cmets 中所述,E 被作为浮点数的一部分读取。您可以使用此代码将浮点数作为字符串读取,然后将其转换为浮点数:

void printLine(char* line) {
    char lat, lon;
    unsigned int year, month, day;
    float temp, uncertainty;
    char latitude[100], longitude[100];
    float latFloat, longFloat;
    char country[100], city[100];
    char blah[100];
    int result;
    result = sscanf(line, "%u-%u-%u,%f,%f,%[^,],%[^,],%[0-9.]%c,%[0-9.]%c", &year,
        &month, &day, &temp, &uncertainty, city, country, latitude, &lat, longitude, &lon);

    latFloat = atof(latitude);
    longFloat = atof(longitude);

    printf("%u-%u-%u,%f,%f,%s,%s,%f%c,%f%c\n", year, month, day, temp, uncertainty,
        city, country, latFloat, lat, longFloat, lon);

    printf("sscanf read %i variables\n", result);
}

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多