Monthly Archives: June 2014

C scanf with comma separated values.

Unlike scanf function family in MATLAB, C scanf doesn’t consider the comma(,) as a delimiter for the specifier “%s.”

Let’s say we have a data file as follows.

Spiderman,Parker,99
Superman,Ken,89
Batman,Wayne,79

The following code will not work. The variable “first_name” will have the whole line “Spiderman,Parker,99” since it thinks there is no delimiter in the line.

char first_name[50], last_name[50];
int grade;
FILE *fp = fopen("data.csv", "r");
fscanf(fp, "%s,%s,%d\n", first_name, last_name, &grade);

Here is a way to make scanf functions think the comma (,) is a delimiter.

fscanf(fp, "%[^,],%[^,],%d\n", first_name, last_name, &grade);