Sunil Kumar
Sunil Kumar

Reputation: 416

Working of sscanf

There is a big string. I want to store different parts of this in different variables. But it seems that either my understanding is not clear or there is a bug. Please help.

here is my section of code.

char sample[] = "abc,batsman,2,28.0,1800";

char name[10] ,speciality[10];
float batavg;
int pos, runs,j;

j = sscanf(sample,"%s,%s,%d,%f,%d", name, speciality, pos, batavg, runs);

printf("%s,%s,%d,%f,%d", name, speciality, pos, batavg, runs);
printf("\n%d\n",j);

Output

Some garbage values with the value of j = 1 in the above case is shown.

How can I settle this?

Upvotes: 0

Views: 181

Answers (2)

John Bollinger
John Bollinger

Reputation: 180048

The scanf() family of functions require you to pass pointers to the locations where the scanned fields should be stored. That just works when you're scanning into a char array (field descriptor %s) because the name of a char array is converted to a pointer automatically, but for other kinds of fields you need to use address-of operator (&).

Additionally, as iharob first observed, the %s descriptor expects fields to be delimited by whitespace. You can get what you want via the %[] descriptor:

j=sscanf(sample,"%[^,],%[^,],%d,%f,%d",name,speciality,&pos,&batavg,&runs);

Upvotes: 6

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The "%s" specifier in *scanf() family of functions scans all the characters until a white space happens.

So the first "%s" is consuming the whole string, that's why j == 1, you must check the value of j before printing, since all the other parameters are uninitialized at the moment of printing.

You need a different format specifier, namely

sscanf("%[^,],%[^,],%d,%f,%d", name, speciality, &pos, &batavg, &runs);

Upvotes: 1

Related Questions