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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With