Belrog Belrog - 1 year ago 149
C Question

How do I parse out the fields in a comma separated string using sscanf while supporting empty fields?

I have a comma separated string which might contain empty fields. For example:


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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download