Problem of sscanf sequence of its detination variables

F

fl

Hi,
Although I have check the description of sscanf, I am still puzzled at
the following lines which are from someone else. 'str' is string
"1x10". sscanf should assign the string sequencially to prop, n and
junk from my understanding. The example is in a float number, integer
and char. sscanf assigns the destination variables according to the
format sequence?


..................
int n;
double prop, sum;
char junk;

scan_num = sscanf(str, "%lgx%d%c", &prop, &n, &junk);
...................
 
E

Eric Sosman

Hi,
Although I have check the description of sscanf, I am still puzzled at
the following lines which are from someone else. 'str' is string
"1x10". sscanf should assign the string sequencially to prop, n and
junk from my understanding. The example is in a float number, integer
and char. sscanf assigns the destination variables according to the
format sequence?

Yes. The first conversion specifier in the format string converts
some amount of input and stores the result where the first pointer
argument points. Then the second specifier stores its result where
the second pointer points, and so on. (There are a few oddball cases
for conversion specifiers like "%%" and "%*d", but that's the general
outline.)

The function returns a count of the successful conversions. You
can use this count to see whether anything went wrong.
int n;
double prop, sum;
char junk;

scan_num = sscanf(str, "%lgx%d%c",&prop,&n,&junk);

Let's start by decomposing the format string into its parts:
There's a conversion specifier "%lg", a matching character "x",
another specifier "%d", and a third specifier "%c". Three conversion
specifiers, three pointer arguments, and the types match properly
("%lg" converts a `double', the corresponding pointer is a `double*',
and so on). So far, all is well.

Now let's work through the given input, "1x10". The "%lg"
specifier consumes the "1" and converts it to a `double', which is
stored in `prop'. The "x" matches the "x" in the input, converting
and storing nothing. The "d" consumes all of the "10" and converts
it to an `int', which it stores in `n'. But then all the input has
been consumed, and there's nothing left for the "%c" directive to
work with. So the "%c" conversion fails and does not store anything
in `junk', and sscanf() returns 2 to count the two successful
conversions out of three attempted.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top