LearnFrenzy
Sign in Take a free test

C Input / Output · Input/Output Programs · Question 2

Keep asking until a valid integer is entered in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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).

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links