problems with scanf() and gets()

John Gordon gordon at osiris.cso.uiuc.edu
Fri Jun 7 04:21:18 AEST 1991


jhp at apss.ab.ca (Herbert Presley) writes:

>scanf() and gets() will not accept keyboard input in the same program if
>scanf() is used first.  I am using scanf() to accept an integer from the
>keyboard and gets() to accept a string.  Because scanf() aborts input at
>the first whitespace, you cannot enter a sentence string (or, is this something
>I am doing wrong because of my inexperience)?  So in instances where you are
>attempting to enter a formatted integer variable and a string in the same
>program, I find that using scanf() first makes gets() skip the wait for
>keyboard input.

	Here is your problem: scanf() leaves a carriage return hanging in the
input buffer.  Since gets() ends on a carriage return, it picks this up
immediately and quits.  My solution is to do a getchar() right after a scanf()
and suck up the floating carriage return.

---
John Gordon
Internet: gordon at osiris.cso.uiuc.edu        #include <disclaimer.h>
          gordon at cerl.cecer.army.mil       #include <clever_saying.h>



More information about the Comp.lang.c mailing list