[net.unix] ugliness in scanf

cdl@mplvax.UUCP (Carl Lowenstein) (05/06/85)

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

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