read comma-separated input with `scanf()`

Moonlit picture Moonlit · Feb 26, 2013 · Viewed 60.6k times · Source

I have the following input:

AG23,VU,Blablublablu,8
IE22,VU,FooBlaFooBlaFoo,3
and so on...

I want it to "parse" with scanf() using some code like this:

char sem[5];
char type[5];
char title[80];
int value;

while(scanf("%s,%s,%s,%d", sem, type, title, &value) == 4) {
 //do something with the read line values
}

But the execution of the code gives me: illegal instruction

How would you read a comma-separated file like this?

Answer

hmjd picture hmjd · Feb 26, 2013

The comma is not considered a whitespace character so the format specifier "%s" will consume the , and everything else on the line writing beyond the bounds of the array sem causing undefined behaviour. To correct this you need to use a scanset:

while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4)

where:

  • %4[^,] means read at most four characters or until a comma is encountered.

Specifying the width prevents buffer overrun.