0

I've been writing a program that takes an input and checks if the number is even or odd and outputs an error message if the input is a character not a number my initial code was:

int main()
{
    int x;
    int check = scanf("%d", &x);
    printf("input: ");
    while(check != 1){ //means that the input is inappropriate 
       printf("Error!: unexpected input\n"); 
       printf("input: ");
       check = scanf("%d", &x);
    }
    if(x%2 == 0){
    printf("It's even\n");
    }else{
    printf("It's odd\n");
    }
return 0;
}

when I run an infinite loop printing "Error!: unexpected input\n" but when I put the following statement in the while loop it works properly the statement is : scanf("%s",&x); can somebody explains this behavior?

Mat
  • 202,337
  • 40
  • 393
  • 406
NerdyKoala
  • 25
  • 6

1 Answers1

0

int check = scanf("%d", &x); does not consume the "input is a character not a number", leaving that input in stdin for the next input function. Since the next input function is check = scanf("%d", &x);, it does not consume the offending data and so the cycle repeats.

Code needs to read the "input is a character not a number" with something other than scanf("%d", ...)


Rather than mess with a little fix, recommend never using scanf(). Read input with fgets() or getline() and then parse with ssscanf(), strtol(), etc.

int main(void)     {
    int x;
    char buf[100];
    while (printf("input: "), fgets(buf, sizeof buf, stdin) != NULL) {
      int check = sscanf(buf, "%d", &x);
      if (check == 1) break;
      printf("Error!: unexpected input\n"); 
    }
    if(x%2 == 0){
      printf("It's even\n");
    }else{
      printf("It's odd\n");
    }
  return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256