I am working on a program which requires a lot of simple input validation. Basically I ask several questions to which the user must input either 1, 2, or 3. Any input that is other than this will be rejected and the user must be prompted to enter either 1,2, or 3. I am new to C and programming in general so please keep that in mind! Here's the code:
Code:
int maritalstatus
maritalstat:
printf("Enter \"1\" if Single, \"2\" if Married, or \"3\" if you are Married but you want to withhold at the Single Rate: ");
//check to see if input is not an integer.
if (scanf("%d", &maritalstatus) != 1)
goto maritalstat;
//if input is an integer the switch statement starts.
switch(maritalstatus)
{
case 1 : break;
case 2 : break;
case 3 : break;
default: goto maritalstat;
}
There are a few problems I am having when I execute this. First of all when I enter a non integer as an input, such as an alphabetic character, an infinite loop seems to start. The screen keeps scrolling until I halt the program. Second of all even if I enter a 1, 2, or 3, the switch loop does not break. It goes back to the beginning and asks me to enter an input.
I would appreciate if if you could tell me what I am doing wrong or perhaps suggest a better way of doing this. Thanks