scan3.c

/*
 * simple program using scanf to read an integer
 * this one works correctly
 *
 * Matt Bishop, ECS 36A
 *
 * April 22, 2024
 *      first version
 */
#include <stdio.h>

/*
 * the program
 */
int main(void)
{
        int n;  	/* what is read */
	int res;	/* return value of scanf */

	/* try to read an integer, looping until you do */
	/* or until you read an EOF (here or below)     */
	while((res = scanf("%d", &n)) != 1 && res != EOF){
		/* 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')
			;
	}

	/* if EOF, nothing read; otherwise, print the number */
	if (res != EOF)
		printf("I read %d\n", n);

	/* quit */
	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