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.
sscanf() — Read Data For more information, see Understanding CCSIDs and Locales. Description. The sscanf() function reads data from buffer into the locations that are given by argument-list . Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string .
The sscanf() function allows us to read formatted data from a string rather than standard input or keyboard. Its syntax is as follows: Syntax: int sscanf(const char *str, const char * control_string [ arg_1, arg_2, ... ]); The first argument is a pointer to the string from where we want to read the data.
The scanf function reads data from standard input stream stdin into the locations given by each entry in the argument list. The argument list, if it exists, follows the format string. The sscanf function reads data from buffer into the locations given by argument list.
No terminating null is added. Pointer to char large enough for input field. Like c , a sequence of bytes of type char (signed or unsigned), except that white space characters are not allowed, and a terminating null is always added.
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.
%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
.
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