I have a comma separated string which might contain empty fields. For example:
1,2,,4
Using a basic
sscanf(string,"%[^,],%[^,],%[^,],%[^,],%[^,]", &val1, &val2, &val3, &val4);
I get all the values prior to the empty field, and unexpected results from the empty field onwards.
When I remove the expression for the empty field from the sscanf(),
sscanf(string,"%[^,],%[^,],,%[^,],%[^,]", &val1, &val2, &val3, &val4);
everything works out fine.
Since I don't know when I'm going to get an empty field, is there a way to rewrite the expression to handle empty fields elegantly?
I made a modification for tab delimited TSV files, hopefully it may help:
And the ouput:
Here is my version to scan comma separated int values. The code detect empty and non-integer fields.
Result:
Put a '*' after the '%' to skip reading. In addition it is possible to read only 3 characters noting '%3s' for example.
man sscanf:
(emphasis added).
This looks like you are currently dealing with CSV values. If you need to extend it to handle quoted strings (so that fields can contain commas, for example), you will find that the
scanf
-family can't handle all the complexities of the format. Thus, you will need to use code specifically designed to handle (your variant of) CSV-format.You will find a discussion of a set CSV library implementations in 'The Practice of Programming' - in C and C++. No doubt there are many others available.
If you use
strtok
with the comma as your separator character you'll get a list of strings one or more of which will be null/zero length.Have a look at my answer here for more information.