Re: Is there a better way for scanf?
- From: Dave Thompson <david.thompson1@xxxxxxxxxxxxxxxx>
- Date: Mon, 13 Jun 2005 04:01:29 GMT
On 8 Jun 2005 19:32:02 -0700, "Robert Gamble" <rgamble99@xxxxxxxxx>
wrote:
> russfink@xxxxxxxxx wrote:
> > Easiest method is use the * modifier which means to scan, but do not
> > assign, the input. The format string becomes " %2s%*s": the leading
> > space means skip whitespace (including newlines);
True but unnecessary; %s _also_ skips leading whitespace, as does
every conversion except %[...] and %c .
> > %2s means read a string of 2 characters (ending with null);
>
> scanf reads characters, not strings, from the standard input stream and
> does not expect null character termination.
>
Right. Although, *scanf %s (and %[..] but not %c) does _add_ a null
character terminator to the value it stores. Note that this is not
counted in the maximum-width specification; the OP correctly had
char A [3] matched to scanf %2s .
> > %*s means read all further characters on the line, but don't assign.
>
> No, it doesn't. The %*s means read and discard a sequence of
> "non-white-space characters". If the string in question is "this
> doesn't work", the " %2s" will consume the "th" and the subsequent
> "%*s" will consume the "is", leaving the rest of the input on the
> stream.
>
> > The positional parameter is
> > NULL in this case (though it can be anything).
>
> No, the positional parameter is not NULL, nor can it "be anything".
> There must not be a parameter provided at all for an assignment
> suppression, doing so will invoke undefined behavior if there is
> another conversion later in the same format string that does expect a
> corresponding parameter. (It may cause undefined behavior in every
> case, I don't feel like looking up the details)
>
To be precise, a star-suppressed conversion does not 'use up' a
variable argument, so any such argument is matched with the next
unsuppressed conversion if there is one and it is executed; and if
that argument is not valid for that conversion (and NULL in particular
is not valid for any conversion) it's UB. If the bogus argument isn't
used, it is safely ignored; 7.19.6.2p2, at least if we understand
'exhausted' to include terminated due to mismatch or input error as I
think we must given p4 and 7.19.6p1.
- David.Thompson1 at worldnet.att.net
.
- References:
- Is there a better way for scanf?
- From: QQ
- Re: Is there a better way for scanf?
- From: russfink
- Re: Is there a better way for scanf?
- From: Robert Gamble
- Is there a better way for scanf?
- Prev by Date: Re: Bit twiddling
- Next by Date: Re: sorting 2d arrays using qsort
- Previous by thread: Re: Is there a better way for scanf?
- Next by thread: Re: Is there a better way for scanf?
- Index(es):