I am trying to read a CSV file in c89
using scanf
:
FOO,2,3
BAR,5,4
...
This is what I have tried:
#include <stdio.h>
int main() {
char code[10];
double a,b;
while( scanf("%s,%lf,%lf", code, &a, &b)!=EOF ) {
printf("> %s\n", code);
printf("> %s,%lf,%lf\n", code, a, b);
}
return 0;
}
This is the output I get:
$ ./a.out
A,2,3
> A,2,3
> A,2,3,0.000000,0.000000
B,5,4
> B,5,4
> B,5,4,0.000000,0.000000
$
This is the output I was expecting from the above code:
$ ./a.out
A,2,3
> A
> A,2.000000,3.000000
B,5,4
> B
> B,5.000000,4.000000
$
Edit
As per the comment provided I have tried:
#include <stdio.h>
int main() {
char code[10];
double a,b;
while( scanf("%9[^,],%lf,%lf", code, &a, &b)!=EOF ) {
printf("> %s\n", code);
printf("> %s,%lf,%lf\n", code, a, b);
}
return 0;
}
And I get:
$ cat > test.txt
A,2,3
B,4,5
C,5,6
$ cat test.txt | ./a.out
> A
> A,2.000000,3.000000
>
B
>
B,4.000000,5.000000
>
C
>
C,5.000000,6.000000
>
>
,5.000000,6.000000
$
Apparently the first record is properly processed but not the subsequent ones.
Also I have the question about what the 9
does and if the whole %9[^,]
is part of c89
.