problems with scanf() and gets()

D'Arcy J.M. Cain darcy at druid.uucp
Fri Jun 7 23:38:25 AEST 1991


In article <1991Jun6.182118.16211 at ux1.cso.uiuc.edu> John Gordon writes:
>jhp at apss.ab.ca (Herbert Presley) writes:
>>scanf() and gets() will not accept keyboard input in the same program if
  [ description of the usual scanf/gets problem deleted ]
>	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.

Actually he has two problems.  First he didn't read the FAQ and secondly
he is getting advice from people who haven't read the FAQ.  Here is the
definitive answer:

              READ THE FREQUENTLY ASKED QUESTIONS

In particular question #77 answers this:

77.  When I read from the keyboard with scanf(), it seems to hang until
     I type one extra line of input.

A:   scanf() was designed for free-format input, which is seldom what
     you want when reading from the keyboard.  In particular, "\n" in a
     format string does not mean "expect a newline", it means "discard
     all whitespace".

     It is usually better to fgets() to read a whole line, and then use
     sscanf() or other string functions to parse the line buffer.

If you are going to answer questions please read the FAQ first.  This is
also excellent advice before asking one.

-- 
D'Arcy J.M. Cain (darcy at druid)     |
D'Arcy Cain Consulting             |   There's no government
Toronto, Ontario, Canada           |   like no government!
+1 416 424 2871                    |



More information about the Comp.lang.c mailing list