Search code examples
ccycle

Strange working cycle in C


int n = 0;
int temp = 0;

while ((temp != 1) || (n <= 0)){
  puts("enter array count");
  temp = scanf("%d", &n);
  printf("\n%d\n", temp);
}

I need to check input value for the fact it must be an integer and be > 0.

scanf returns count of success set values and if it's not an integer it will return 0.

So the problem is that when I'm typing any char except number it starts non-finished cycle

Why?


Solution

  • When you type something invalid, such as a character, for scanf("%d", &n);, the scanf fails, returns 0, and leaves the invalid data in the stdin. In the next iteration scanf sees this invalid data prevailing in the stdin, fails again and this process is repeated.

    The fix is to clear the stdin in each iteration of the loop. Add

    int c;
    while((c = getchar()) != '\n' && c != EOF);
    

    or

    scanf("%*[^\n]");
    scanf("%*c");
    

    just after the scanf to clear the stdin.