
Newbie with scanf question
Quote:
>How do I do this without scanf
>puts("Please enter an integer");
>scanf("%d",&number);
>If I type in a letter by accident the program will terminate. Correct?
Nope. If the letter is not the first character, scanf will happily
convert the digits preceding it and leave it in the input buffer, to be
read by the next scanf, which will fail and leave it there for the next
scanf and so on... :-(
scanf is a function that returns the number of successful conversions
performed, 1 in your case, or 0 if the conversion failed because of the
wrong character.
Quote:
>How would I do the above without scanf??
Other people have already mentioned alternatives (which may or may not
be too esoteric for you). I'll show you how to do it with scanf:
int rc;
do {
rc = scanf("%d", &number);
while (getchar() != '\n') ; /* get rid of the characters left */
} while (rc < 1); /* by scanf in the input buffer */
This assumes that you never press your end-of-file key when the program
expects input from you. Otherwise, things get slightly more complicated:
you have to check if either scanf or getchar has returned EOF and abort
the program (or take whatever action is appropriate) if this happens.
Dan
--
Dan Pop
CERN, IT Division
Mail: CERN - IT, Bat. 31 1-014, CH-1211 Geneve 23, Switzerland