/*
* simple program using scanf to read an integer
* done right another way
*
* Matt Bishop, ECS 36A
*
* April 22, 2024
* first version
*/
#include <stdio.h>
/*
* the program
*/
int main(void)
{
int n; /* what is read */
char buf[10]; /* input buffer */
/* try to read an integer, looping until you do */
#include <stdio.h>
int main(void)
{
int n;
/* read a line, looping until you break or read EOF */
while (fgets(buf, 10, stdin) != NULL){
/* not EOF -- *now* get the integer, if any */
if (sscanf(buf, "%d", &n) != 1){
/* you didn't; report an error */
fprintf(stderr, "Enter a positive integer\n");
}
else{
/* you got it; print it and drop out of the loop */
printf("I read %d\n", n);
break;
}
}
/* phew, all done! */
return(0);
}
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |