problems with scanf() and gets()

Chris Riley 201 564-2516 crr at cbnewsm.att.com
Sat Jun 8 03:52:50 AEST 1991


In article <2759 at apss.apss.ab.ca> jhp at apss.ab.ca (Herbert Presley) writes:
>I kinda feel intimidated because, like most new programmers, I am probably
>asking a question that has a VERY simple response, and I can't help but feel
>that it's a problem that I am creating by my lack of knowledge.

That's ok.  That's what stuff like comp.lang.c is for.

>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.

It is generally unsafe to use scanf() to read from the keyboard.  Since
scanf() will loose data if the data isn't formatted the way it likes, it is
dangerous to use scanf() unless the data you are reading was generated by
another program.

A safer method is to read a string with gets() or fgets(), then use
sscanf() to look for the data in the string.  If the data isn't in the
right format, you have a chance to try to figure out what it is.

-- 
Chris Riley            chris.riley at attbl.att.com



More information about the Comp.lang.c mailing list