Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input validation in C

I'm writing a program in C. In the program, the user has to choose a number, either 1, 2 or 3. I would like to construct the code so that when the user enters in a number that isn't 1, 2 or 3, he/she will be told "Invalid selection - choose again" and then they will be brought back to the start of the program:

int main() {

    int choice;
    char response, Y, N;

    printf("Choose a shape from the following:\n 1.Sphere\n 2.Cone\n 3.Cylinder\n");

    scanf("%d",&choice);

    if(choice==1||choice==2||choice==3) {
        printf("Enter the radius, r\n");                             
    } else
        printf("Invalid selection, choose again.\n");

}

What I would like is that after "Invalid selection, choose again" appears, the user is brought back to the start of the program, so they can input their choice again. How would I do this?


1 Answers

Here is what you do:

int choice;
char response, Y, N;
for (;;) {
    printf("Choose a shape from the following:\n 1.Sphere\n 2.Cone\n 3.Cylinder\n");

    scanf("%d",&choice);

    if(choice==1||choice==2||choice==3) {
        break;                    
    }
    printf("Invalid selection, choose again.\n");
}

Once this loop is over, prompt for the radius. You will nearly certainly need another loop to prevent the input of negative values for the radius, so do not prompt for it in the same loop.

like image 190
Sergey Kalinichenko Avatar answered Mar 26 '26 23:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!