Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site mplvax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!decvax!ittvax!dcdwest!sdcsvax!sdcc3!mplvax!cdl From: cdl@mplvax.UUCP (Carl Lowenstein) Newsgroups: net.unix,net.lang.c Subject: ugliness in scanf(3) Message-ID: <189@mplvax.UUCP> Date: Mon, 6-May-85 12:38:54 EDT Article-I.D.: mplvax.189 Posted: Mon May 6 12:38:54 1985 Date-Received: Wed, 8-May-85 03:31:57 EDT References: <10195@brl-tgr.ARPA> <220@ki4pv.UUCP> <10432@brl-tgr.ARPA> Reply-To: cdl@mplvax.UUCP (Carl Lowenstein) Organization: Marine Physical Laborator of SIO at UCSD Lines: 45 Xref: watmath net.unix:4430 net.lang.c:5164 Summary: scanf(3) chokes on bad input The same ugly undocumented behavior has shown up with the stdio library using 3 C compilers on 3 operating systems (DECUS C on RT-11, cc on SysV, (3b2), and cc on 4.2BSD (vax). First to quote the documentation: "These functions return . . . a short count for . . . illegal data items" (SysV). ". . . if conversion was intended, it was frustrated by an inappropriate character in the input." (4.2BSD). Ok, but the character pointer is never advanced past that inappropriate character, so the poor user's program is either stuck in an infinite loop or else it has to advance the pointer to get going again. Surely others have noticed this in the past. Below is a little test program which shows a workaround. Without the getchar(), it will loop until you get tired of watching it. Try it with bad octal digits like 8,9,a,b . . . /*-------------------------------------------------------------------------*/ /* scanft.c */ /* * look at bug in scanf */ #include main() { int i, k; for (;;) { printf("\n number: "); k = scanf("%o", &i); printf("scanf returns %d\n",k); if (k == EOF) break; if (k == 0){ i = getchar(); /* flush a character */ printf(" choked on '%c'\n",i); continue; /* go back and ask again */ } printf("value = %o\n", i); } exit(0); } /*-------------------------------------------------------------------------*/ -- carl lowenstein marine physical lab u.c. san diego {ihnp4|decvax|akgua|dcdwest|ucbvax} !sdcsvax!mplvax!cdl