Forum Member
Forum Member

Reputation: 163

sscanf format c++

I have a sscanf statement as

sscanf (fieldname, "%s_%d", name, id);

I am giving input as frog_461 but it displays name as "frog_461" and 0 for id. Can you please suggest the correct way to give input to make this statement work? Like in the above example how should I give my input so that name="frog" and id=461. Thanks.


I appreciate all your input. Currently I cannot modify the code, therefore I am not trying to find an alternate way of getting it to work. I am just checking if this code was working earlier and if yes then what input the user must have given to make it work. Thanks.

Upvotes: 5

Views: 7512

Answers (4)

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74340

The answers given so far highlighting sscanf's limitations are wrong! There is a correct way to do this with sscanf:

sscanf(fieldname, "%[^_]_%d", name, &id); 

The %[^_] means to read until an underscore character is encountered. See the entry for [ in the man page for scanf.

Also, notice the ampersand in front of id it is necessary to pass a pointer to id, in order to change it because of C's pass by value semantics.

By the way, this is really a C question and not a C++ one, so you should have probably tagged it as such. If you are using C++, there are much better options than sscanf for parsing.

Upvotes: 14

Perhaps the poster knows that the "identifier" part of his token is only with (English lower-cases) letters, then he could try

char name[32];
memset (name, 0, sizeof(name));
if (sscanf(fieldname, "%31[a-z]_%d", name, num)>=2) {
   /* do something */
} else {
   /* bad fieldname */
}

Be careful with sscanf for C strings (i.e. char arrays) about string buffer overflow; always give a maximal size.

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96119

scanf isn't a general regex parser it only handles whitespace.

You need to split the input string using strtok() or similar, or if you know the format just replace _ with " "

Upvotes: -1

Dabbler
Dabbler

Reputation: 9863

%s reads until it encounters whitespace, it doesn't know to stop at the underscore. One way to do this would be to search for the underscore yourself with strchr. Then you know where the first part of the string ends, and the number can be read with %d.

Upvotes: 1

Related Questions