Moonlit
Moonlit

Reputation: 5409

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?

Upvotes: 23

Views: 85509

Answers (3)

TIRTHANKAR NATH
TIRTHANKAR NATH

Reputation: 1

you can use scanf("%d%*c"); // to suppress any character you want to skip taking input

suppose scanf("%d%*c%d",&a,&b); // i/p is 31,42 %*is used for suppression o/p: 3142

it may be any character / , . .......

Upvotes: 0

Andrés AG
Andrés AG

Reputation: 419

The problem that you are having is because when you say

 scanf("%s,%s,%s,%d", sem, type, title, &value) 

what happens is that you are trying doing is that you are fitting all the line into the first string which is just 5 characters. Therefore the sem[5] overflows, and soes all sorts of funny things. To avoid this problem, I tried using the expression %[^,], but it is not quite working. The best bet is to use something like

while(scanf("%s%c%s%c%s%c%d", sem, &ch, type, &ch, title, &ch, &value) != EOF)

Then you can just discard the ch. However bear in mind that is better to use other functions to reading input such as getchar(), and things like that, which are much faster and safer in some sense.

Upvotes: -2

hmjd
hmjd

Reputation: 121971

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.

Upvotes: 59

Related Questions