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

Belrog picture Belrog · Oct 2, 2009 · Viewed 52k times · Source

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?

Answer

ChrisF picture ChrisF · Oct 2, 2009

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.