
Spaces in scanf format string
Quote:
>I have a question about the format string while using scanf. My K&R2 says
>that the format string may contain blanks which are ignored (pg 157).
K&R2's description of scanf is incorrect (this is a well-known fault). From
the standard:
"A directive composed of white-space character(s) is executed by reading
input up to the first nonwhite-space character (which remains unread), or
until no more characters can be read"
So in effect white-space in the format string causes white-space in the input
data to be skipped.
Quote:
>However, on two very different platforms the scanfs in the following
>program behave very differently. The only difference is the trailing space
>in the format string.
>#include <stdio.h>
>int main(void)
>{
> int i;
> printf("int: ");
> scanf("%d", &i);
> printf("you entered %d\n", i);
> printf("another int: ");
> scanf("%d ", &i);
> printf("you entered %d\n", i);
> return(0);
>}
>The second scanf hangs waiting for a second input.
Right - it continues to skip white-space until it encounters a non-white-
space character (or error or end-of-file). It will wait for further input
until one of these conditions is met.
Quote:
> I know there are
>problems with scanf and I generally use fgets, but this seems to contradict
>K&R, and it stumped me for quite a while this morning. Can anyone shed any
>light on this?
>Are my two compilers doing something wrong, or am I misreading K&R?
Shock horror, it is the 3rd alternative! :-) Don't worry though, there isn't
much else wrong with K&R2 - misuse of reserved identifiers in examples is
all I can think of immediately.
--
-----------------------------------------
-----------------------------------------