Reputation: 11
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?
P.S. : 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?
Upvotes: 1
Views: 10216
Reputation: 3209
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
Upvotes: 1