I need to read a csv file that has missing values. The program is suppose to assign the values from the csv to 5 arrays. The program works fine when all fields have values. The problem is when the program encounters ,, instead of a value it skips the pointer assignment. When it encounters a missing value it is suppose to assign -9 as a value. I'm using vc 6.0 to build a console application, below is the code, the input file and the current output.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
void main (void)
{
int i,one[4],three[4],five[4];
float two[4],four[4];
char line[25];
char sx[]=",",*s1;
FILE *ifp;
ifp=fopen ("test.csv","r");
i=0;
while(fgets(line, sizeof line, ifp))
{
s1=strtok(line,sx);
if (s1==NULL) one[i]=-9;else
one[i]=atoi(s1);
s1=strtok(NULL,sx);
if (s1==NULL) two[i]=-9.0;else
two[i]=atof(s1);
s1=strtok(NULL,sx);
if (s1==NULL) three[i]=-9;else
three[i]=atoi(s1);
s1=strtok(NULL,sx);
if (s1==NULL) four[i]=-9.0;else
four[i]=atof(s1);
s1=strtok(NULL,sx);
if (s1==NULL) five[i]=-9;else
five[i]=atoi(s1);
printf("%d %f %d %f %d\n", one[i], two[i],three[i],four[i],five[i]);
}++i;
}
input file test.csv
1,2.0,3,4.0,5,
1,,3,,5,
1,2.0,,4.0,,
output
1 2.000000 3 4.000000 5
1 3.000000 5 0.000000 -9
1 2.000000 4 -9.000000 -9