Problem of sscanf sequence of its detination variables

Discussion in 'C Programming' started by fl, Dec 24, 2011.

1. flGuest

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);
...................

fl, Dec 24, 2011

2. Eric SosmanGuest

On 12/24/2011 10:30 AM, fl wrote:
> 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.

--
Eric Sosman
d

Eric Sosman, Dec 24, 2011