Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Ike Naar <ike@iceland.freeshell.org> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: about scanf() |
| Date | 2012-07-17 06:23 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <slrn3vfsk0a17j.85s.ike@iceland.freeshell.org> (permalink) |
| References | <85a02bae-76e2-48e6-8d4c-175317166861@googlegroups.com> |
On 2012-07-17, ?? <wpwupingwp@gmail.com> wrote:
> int get_int(void)
> {
> int input;
> char ch;
> while(scanf("%d",&input)!=1)
> {
> while((ch=getchar())!='\n')
> putchar(ch);
> printf(" is not an integer.\nPlease enter an integer value, such as 25,-178 or 3: ");
> }
> return input;
> }
>
> ///////////////////////////////////////////////////
> Here is the code from C Primer Plus, when the input is not an integer, it print the wrong input.
> My question is, if scanf() gets the wrong input, it doesn't through out the wrong input, but give it to next receiver?
That is correct, but scanf only has to "unread" (push back into
the input stream) a single character, i.e. the first character that
does not match the format specifier.
For instance, if the input to the "%d" format is "silly", scanf
notices that an integer cannot start with 's', pushes back the 's'
into the input stream, and returns unsuccessfully.
If the input is "123xyz", scanf notices that "123" is the longest
prefix that matches the "%d" format, and that "123x" doesn't match
the format, so "123" is converted to an int, and the 'x' is pushed
back into the input stream.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
about scanf() 吴平 <wpwupingwp@gmail.com> - 2012-07-16 18:51 -0700
Re: about scanf() Ike Naar <ike@iceland.freeshell.org> - 2012-07-17 06:23 +0000
Re: about scanf() 吴平 <wpwupingwp@gmail.com> - 2012-07-23 00:21 -0700
csiph-web