I am trying to run a program whereby user can only enter 1 or 2. If the user enters any other numbers or alphabets, it should prompt the user back to entering input again. I have tried the following code and it works if user enter an integer which is not 1 or 2, but the whole program will go haywire if entered any alphabets. I tried to validate with
if == 0 but doesnt work as well. Does anyone have any idea?
int getUserInput(){ printf("1: You have chosen 1.\n"); printf("2: You have chosen 2.\n\n"); printf("Enter an option: "); scanf("%d", &userSel); if(userSel!= 1 && userSel!= 2){ printf("You have entered an invalid input. Please try again.\n"); getUserInput(); } else{ printf("Enter a number: "); scanf("%d", &userNo); } printf("userSelection: %d\n", userSel); printf("1userNumber: %d\n", userNo); return 0; }