chilliefiber
chilliefiber

Reputation: 651

Sscanf not reading identical lines the same way

#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);
}

Some lines it reads properly and some lines it doesn't read the last character. I'm not sure what causes this bug, I'm probably invoking some sort of undefined behaviour but I'm not sure what it is.

Upvotes: 3

Views: 69

Answers (1)

Stephen Docy
Stephen Docy

Reputation: 4788

As mentioned in the comments, the E is being read as part of the float. You can use this code to read the float as a string and then convert it to a float:

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);
}

Upvotes: 2

Related Questions