Mark McIntyre wrote:[color=blue]
> On 2 Feb 2005 14:45:11 -0800, in comp.lang.c , "drM" <mdeh@comcast.net>
> wrote:
>[color=green]
>>It makes sense now...all part of the learning curve. Thanks for your
>>input.[/color]
>
>
> You may also want to consider not using scanf for user input - its not very
> robust or secure. Its often better to use fgets and sscanf. As you've
> found scanf can't handle unexpected input very well.[/color]
An addendum (without wanting to break up old trenches):
scanf() can be used in a moderately safe way (others argue in the
only safe way compared to fgets()+sscanf) if used correctly.
If you want to use scanf(), at least check the return value.
scanf() (and also all other *scanf() functions) returns the number
of input items successfully read.
Examples:
if(scanf("%d",&num)!=1) {
/* error: we did not get our number */
}
if( (ret=scanf("%20s is the number %d",name,&num)) != 2 ) {
/* error: ret 1 .. Name was read correctly
** 0 .. No input item read
** <0 .. encoding or other bad error */
}
See also the FAQ 12.17 ('\n' and ' ' are equivalent for our
purposes) to 12.20; if you follow the fgets() advice maybe also
12.23.
You can start from here:
http://www.eskimo.com/~scs/C-faq/top.html
BTW: Read the _complete_ list of _questions_, better of course
the whole FAQ. No kidding.
[color=blue]
> What does this programme do, if the user types in "one" as the response?
>
> #include <stdio.h>
>
> int main(void)
> {
> int x=1;[/color]
char buffer[80];[color=blue]
>
> printf("think of a number\n");
> while(x > 0)
> scanf("%d", &x);[/color]
{
fgets(buffer, 80, stdin);
sscanf(buffer, "%d", &x);
}
admittedly probably puts less load on your box and
you have not the trouble of having to discard faulty input;
but if you scan with Pop's Device anyway, you will have the
same effect -- without having to ask yourself whether you
left crap from the last input line out there effectively
leading to a different input (compared to what you may have
intended).
Apart from that, scanf() can handle an input "1\n2\n" just
like "1 2\n", which may come in handy.[color=blue]
>
> return 0;
> }[/color]
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.