scan6.c

/*
 * Example of scanf
 * this fixes the bug in the previous program
 *
 * Matt Bishop, ECS 36A
 *
 * April 22, 2024
 *	first version
 */
#include <stdio.h>
#include <string.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 */
	char buf[100];	/* input buffer */


	/*
	 * loop until asked to quit
	 */
	do{
		/* prompt for input */
		printf("> ");
		/* split the scanf into several: */
		/* first reads the integer       */
		if ((retval = scanf("%d", &xint)) == 1){
			/* now see if a float or "xxx" follows */
			if (scanf("%f", &yfloat) == 1){
				retval = 2; /* read int, float */
				printf("Got %d, %f\n", xint, yfloat);
			}
			else if (scanf("%s", buf) == 1 && strcmp("xxx", buf) == 0){
				retval = 1;
				printf("Got %d and xxx\n", xint);
			}
			else{	/* neither -- report the integer */
				retval = 1;
				printf("Got %d\n", xint);
			}
		}
		else if (retval != EOF){ /* not integer *or* EOF */
			retval = 0;
			printf("Didn't get anything\n");
		}
		/* print what scanf returned */
		printf("RETVAL = %d\n", retval);
		/* eat the rest oif 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