Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read comma-separated input with `scanf()`

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?

like image 692
Moonlit Avatar asked Feb 26 '13 14:02

Moonlit


1 Answers

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.

like image 165
hmjd Avatar answered Oct 06 '22 07:10

hmjd