Reputation: 365
I am writing a program that could read a text with csv format and I am having this issue where the sscanf only parses the whole thing as one string when it is separated by ','.
For example, a code snippet below
char str[100] = "Alex,2933,89,";
char name[50] = "";
int id;
double mark;
sscanf(str, "%s,%d,%lf,", name, &id, &mark);
printf("%s\n", name);
printf("%d\n", id);
printf("%f\n", mark);
Output was:
Alex,2933,89,
896
0.000000
Which is clearly not the expected output.
But when str is edited to str = "Alex 2933 89 "
, the code is giving me the correct output.
The working code:
char str[100] = "Alex 2933 89 ";
char name[50] = "";
int id;
double mark;
sscanf(str, "%s %d %lf ", name, &id, &mark);
printf("%s\n", name);
printf("%d\n", id);
printf("%f\n", mark);
Correct Output:
Alex
2933
89.000000
Can I know how do I fix this?
Upvotes: 1
Views: 263
Reputation: 144635
%s
stops at white space, the fact that you put a ,
in the format string does not change this behavior. You should use the %[^,]
conversion specification.
Change the code this way:
char str[100] = "Alex,2933,89,";
char name[50] = "";
int id;
double mark;
if (sscanf(str, "%49[^,],%d,%lf,", name, &id, &mark) == 3) {
printf("%s\n", name);
printf("%d\n", id);
printf("%f\n", mark);
}
Note however that %[^,]
cannot parse empty fields. If the CSV line may contain empty fields, such as ,23,89.0,
sscanf()
will fail to convert name
because no character matches the %[^,]
specification. If you have such lines in the source file, you should parse the string fields manually with strchr()
or strcspn()
.
Upvotes: 1