简体   繁体   中英

C : Reading CSV text file with scanf

I am trying to read some values off a CSV file using scanf() for a program I am writing. Here is how I am doing it currently :

int i, j, id, time1, time2, time3, type, value;

scanf("%d,%d,%d,%d,%d,%d", &id, &time1, &time2, &time3, &type, &value);
printf("%d", value);

For example lets look at this CSV line 5, 14:09:01, 1, 1013 .

scanf() reads in id and time1 correctly, but after that I am getting some weird values for the other variables. For example, value is showing up as 32767 , as well as time2 showing up as 4195536 . Does anyone know what I am doing wrong?

PS : Is there anyway instead of using time1, time2, and time3 to get the time, I could just print that as a string to avoid those extra variables?

File x.csv contains only one line:

5, 14:09:01, 1, 1013

This trivial code would do the job for you - time will be read as a string into a char array. Note that this will read up a comma, so you'll need to get rid of it.

#include <stdio.h>
#include <string.h>

int main(void)
{
    int id, type, value;
    char time[100];
    FILE* f = fopen("x.csv", "r");
    fscanf(f, "%d, %s %d, %d", &id, time, &type, &value);
    size_t len = strlen(time);
    time[len-1] = '\0';  // get rid of comma
    printf("%d %s %d %d\n", id, time, type, value);
    fclose(f);
    return 0;
}

output:

5 14:09:01 1 1013

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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