scan5.c

/*
 * Example of scanf
 * This program has a bug (can you find it?)
 *
 * Matt Bishop, ECS 36A
 *
 * April 22, 2024
 *	first version
 */
#include <stdio.h>

/*
 * and we're off!
 */
int main(void)
{
	int xint;	/* for reading an integer */
	float yfloat;	/* for reading a floating point number */
	int retval;	/* return value from scanf */
	int c;		/* used to eat rest of line */


	/*
	 * loop until asked to quit
	 */
	do{
		/* prompt for input */
		printf("> ");
		/* see if they entered an int and a float */
		if ((retval = scanf("%d %f", &xint, &yfloat)) == 2)
			printf("Got %d %f\n", xint, yfloat);
		/* nope -- see if it is an integer follow ed by "xxx" */
		else if ((retval = scanf("%d xxx", &xint)) == 1)
			printf("Got %d\n", xint);
		else	/* nope -- report it */
			printf("Didn't get anything\n");
		/* print what scanf returned */
		printf("RETVAL = %d\n", retval);
		/* ignore the rest of the line */
		while((c = getchar()) != '\n' && c != EOF)
			;
	} while(retval != EOF);

	/*
	 * goodnight, Irene :)
	 */
	return(0);
}



UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh