-2
#include <stdio.h>

int main() {
    int i;
    while (1) {
        printf("Enter no?\n"); // step -1

        if (scanf(" %d", &i) > 0)   // step-2
            printf("Num=%d\n", i);
        else
            printf("Entered character.Pls enter int\n");
    }
}

I want to continue the scan again if user entered a value other than integer when I run the above code with a char input it is running infinite loop. Please suggest why or any solution ...?

Stargateur
  • 24,473
  • 8
  • 65
  • 91

2 Answers2

0

If you enter a character say a for the above program it will not match with %d so it will remain in the buffer. The next time in the loop, it will again not match %d and you will enter an infinite loop.

What you can do, is read from the buffer until you encounter a newline character. The second loop will remove any characters until and including the newline character.

#include <stdio.h>

int main() {
    int i;
    char dummy;
    while (1) {
        printf("Enter no?\n"); // step -1

        scanf(" %d", &i)
        if (i > 0)   // step-2
            printf("Num=%d\n", i);
        else
            printf("Entered character.Pls enter int\n");

        do{
            scanf("%c",&dummy);
        }while (dummy != '\n');        // Add this loop
    }
}
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • @BLUEPIXY - Fixed it. Can you comment on it from the portability aspect. – Rishikesh Raje Feb 07 '17 at 05:17
  • 1) `scanf(" %d", &i)` --> `scanf(" %d", &i);` 2) `scanf(" %d", &i)` should check the return value. 3) `if (i > 0)` : OP is not limited to positive numbers. Also Even if input fails, this condition may be met. – BLUEPIXY Feb 07 '17 at 05:26
0
#include <stdio.h>

int main() {
    int i;
    while (1) {
        printf("Enter no?\n"); // step -1

        if (scanf_s(" %d", &i) > 0) {   // step-2
            printf("Num=%d\n", i);
            break;
        }
        else {
            printf("Entered character.Pls enter int\n");
            fseek(stdin, 0, SEEK_END);
        }
    }
}
Froz3
  • 3
  • 1
  • 4
  • Note that `fseek(stdin, 0, SEEK_END)` is not reliable (for a related discussion, see http://www.dreamincode.net/forums/topic/230015-does-fseekstdin-0l-seek-end-really-drain-the-input-buffer/). – grek40 Feb 07 '17 at 07:08