0

I have been working on a program which requires integer inputs, but every time a non-integer is accidentally entered, the scanf function stops working or becomes stuck in a loop.

This is an example of what I tried to do:

    int n;
    printf("please enter 0 or 1\n");
top:
    scanf("%i",&n);
    if(n == 0)
    {
        printf("you entered 0!\n");
    }
    if(n == 1)
    {
        printf("you entered 1!\n");
    }
    if(n != 0 && n != 1)
    {
        printf("please enter either 0 or 1.");
        goto top;
    }

The third if is to sends you back to the top if you have not entered the right number, but this doesn't work for letters and other characters. How can you send it back to the top if a non-integer input is given?

  • 1
    Dodge it by entering with `fgets` and applying `sscanf` and checking its return value (research the man page: what is the function return value of `scanf` family?). If you don't get what you want, dump the input string and get another. – Weather Vane Apr 18 '17 at 20:32
  • 1
    "How can you send it back to the top if a non-integer input is given?" --> read the non-integer and throw it away first. – chux - Reinstate Monica Apr 18 '17 at 20:41
  • You should check the return value of `scanf()` to recognize when errors have occurred, such as the input not being numeric. When such a matching failure occurs, you must read at least one character from the standard input -- the one `scanf()` is presently choking on -- else it will just remain there to cause trouble on the next attempt. – John Bollinger Apr 18 '17 at 20:43
  • While it has its usages, `goto` here is just bad coding style. Use a loop! – too honest for this site Apr 18 '17 at 20:53

2 Answers2

0

This can be solved by replacing the scanf("%i",&n); call with the following:

char buffer[256];
char *s = fgets(buffer, 256, stdin);

if (s != buffer)
{
    // Some error occurred
    goto top;
}

int error = sscanf(buffer, "%i", &n);

if (error == 0)
{
    // The string read is not a number!
    printf("please enter either 0 or 1.");
    goto top;
}
beeselmane
  • 1,111
  • 8
  • 26
0

try this

#include <stdio.h>

int main(void){
    int n;
    printf("please enter 0 or 1\n");

    for(;;){
        int status;
        char ch;
        status = scanf("%i%c", &n, &ch);//check return value of scanf, ch : for check rest input
        if(status == EOF){
            printf("Bye!!\n", n);
            return 0;
        } else if(status == 2 && ch == '\n'){
            if(n == 0 || n == 1){
                printf("you entered %i!\n", n);
                break;
            }
        } else {
            while(getchar() != '\n');//clear input
        }
        printf("please enter either 0 or 1.\n");
    }
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70