scan2.c

/*
 * simple program using scanf to read an integer
 * it has fewer problems than the previous
 * but can you find the bug in it?
 *
 * Matt Bishop, ECS 36A
 *
 * April 22, 2024
 *      first version
 */
#include <stdio.h>

/*
 * the program
 */
int main(void)
{
        int n;  /* what is read */

        /* try to read an integer, looping until you do */
	while(scanf("%d", &n) != 1){
		/* you didn't; report an error */
		fprintf(stderr, "Enter a positive integer\n");
		/* ignore the rest of the line */
		while((n = getchar()) != EOF && n != '\n')
			;
	}

	/* print what you read, and quit */
	printf("I read %d\n", n);
	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