Read a positive integer with scanf. On invalid input, discard the rest of the line and ask again. Print its square at the end.
Solution
main.c
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a positive number: ");
int r = scanf("%d", &n);
if (r == EOF)
return 1;
if (r == 1 && n > 0)
break;
printf("invalid\n");
int c;
while ((c = getchar()) != '\n' && c != EOF) /* discard the rest of the line */
;
}
printf("%d squared is %d\n", n, n * n);
return 0;
}
Output Verified by compiling and running
Enter a positive number: invalid
Enter a positive number: invalid
Enter a positive number: 7 squared is 49
When %d fails on "abc", the letters stay in the buffer and would make every later scanf fail too, so they are thrown away up to the newline. The return value separates "no number" (0) from "end of input" (EOF).
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!