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);
Advertisements

About Jaerock

Assistant Professor of Computer Engineering Dept. of Electrical and Computer Engineering Kettering University

Posted on June 11, 2014, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: