0

I have written some C code where you can pick from an answer by inputting a 1 or 2, and if you input a higher number it will bring you back to pick another number just fine. However, if I try to input something that's not a value or a number, like a string or character, the error message at the bottom will repeat infinitely. How can I make my code act the same as if you input a higher number than 1 or 2 when you input any other character? Here the code I use abstracted:

#include <stdio.h>

int a;

int main(){
    b:scanf("%d", &a);
    if(a==1)
    {
        a=0;
    }
    if(a==2)
    {
        a=0;
    }
    else
    {
        a=0;
        printf("\nERROR: Please try again.\n\n");
        goto b;
    }
}

EDIT: Apparently the return value is still stuck in scanf() when it returns to it. How can I clear out scanf() of its return value?

anok
  • 9
  • 2
  • 5
    I'd use a `while` loop for this instead of gotos. Then just `break` from the loop, or set a flag that decides if you keep looping. There are far less legitimate use cases for gotos than there are legitimate ones. – Carcigenicate Feb 09 '17 at 18:50
  • 3
    Ughhh... Goto. Yuck. Learn the right way to do this *now*, before it's too late for you. – Ken White Feb 09 '17 at 18:52
  • 2
    If you get the input with `fgets` and then use `sscanf` on the input string, when the user does not input what you require, you can forget the previous input string and try again. OTOH when using `scanf` any rejected input will remain in the input buffer. **Always** check the return value from the `scanf` family of functions (see man page for what that means). Never assume that the input data is *nice*. – Weather Vane Feb 09 '17 at 18:58
  • You could always use a switch case, with breaks and set default to deal with Invalid Inputs. ie if the user inputs a character – CoderGirl94 Feb 09 '17 at 19:08
  • 1
    If the user types a non-digit, non-blank character, you'll have an infinite loop because `scanf()` leaves the erroneous character in the input for the next input operation to process. You have to check the return value from `scanf()` and clean the gunk out of the input buffer. This is a frequently-asked question — a duplicate. – Jonathan Leffler Feb 09 '17 at 19:12

3 Answers3

-1
#include <stdio.h>

int a;

int isNumeric(const char *str) 
{
    while(*str != '\0')
    {
        if(*str < '0' || *str > '9')
            return 0;
        str++;
    }
    return 1;
}

int main(){

    char inputStr[10];
    while(1){
        scanf("%9s",inputStr);
        if(!isNumeric(inputStr)){
            a=0;
            printf("\nERROR Not a number: Please try again.\n\n");
        }else {
            a = atoi(inputStr);
            if(a==1){
                a = 0;
            }else if(a == 2){
                a == 0;
            }else{
                a=0;
                printf("\nERROR : Please try again.\n\n");
            }
        }`enter code here`
    }
}

Have not tested. But I guess you will get a good idea. check strtol function. That is also useful.

vk3105
  • 94
  • 3
-1

Don't use gotos at all. Instead use while loops:

#include <stdio.h>

int main(void) {
 int a, end = 1; //end determines if the loop should end
 do { //a do-while loop - it's the same as a while loop, except it runs atleast once
  scanf("%d", &a);
  switch (a) { //switches the value of a
  case 1: 
  case 2: printf("You entered %d\n", a);
          end = 0; //sets end to 0, which will end the loop(see below)
          break;
  default: printf("\nERROR: Please try again.\n\n");
  }
 } while (end); //every non-zero value is true, so when I set end to 0, it will end the loop
return 0; //don't forget the return 0: it shows you that your program ran without error
}

So I wrote it that it ends as soon as you type a valid input. You also don't need to set a to zero, as you read it in again every time you run the loop.
EDIT: if you want to check for invalid input such as 5x, you can use the following:

int check, var, error;
char ch;
do {
 error = 0;
 check = scanf("%d%c", &var, &ch);
 if (check != 2 || ch != '\n') {
  printf("Wrong input. Try again -> ");
  error = 1;
  fflush(stdin);
 }
} while (error); 
hm1912
  • 314
  • 1
  • 10
-2

Something like... Note: Obviously 999 is an arbitrary value. Just chosen to give you an example.

#include <stdio.h>


int main(){
int a = 1;
while (a != 999){
  scanf("%d", &a);
  if(a==1)
  {
     a=0;
  }
  if(a==2)
  {
    a=0;
  }
  else if (a != 999)
  {
      a=0;
      printf("\nERROR: Please try again.\n\n");
  }
 } // while()
} // main()
raddevus
  • 8,142
  • 7
  • 66
  • 87
  • 3
    Where is `b` defined? This won't even compile, and I don't think we should be promoting `goto`. – stevieb Feb 09 '17 at 18:58
  • You need to check the return value from `scanf()` too. – Jonathan Leffler Feb 09 '17 at 19:14
  • Relax. Take it easy. It was because I copied the initial code and altered it quickly. The goto is gone. Meant to delete 2nd ref to it from original source. Also, never throw an exception because that is a goto also. :) Think about it, the exception is thrown and code jumps directly to the error location. Uh oh, goto. :) – raddevus Feb 09 '17 at 20:26