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<br />Superman,Ken,89<br />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];<br />int grade;<br />FILE *fp = fopen("data.csv", "r");<br />fscanf(fp, "%s,%s,%d\n", first_name, last_name, &amp;grade);

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *