replace drop by loop

Asked

Viewed 81 times

0

I am making an options menu, with input option 1 or 0 and I want to appear an error when not typed 1 or 0, and so on until the user chooses a valid option and so the program redirects the user to the chosen screen, I managed to structure the code using goto, however I wonder if there was some way to use some loop instead of goto, I couldn’t and I only have goto.

void main()
    {

            int p1, s2, s3;

            system("clear");
            printf("Digite:\n[1] Para acessar o menu\n[0] Para sair do programa\n\n>>> ");
            scanf("%i", &p1);

            switch (p1)
            {       

                    case 0:
                    exit:   
                    system("clear");
                    printf("Saindo\n\n");
                    break;  

                    //Pagina do Menu
                    case 1: 
                    menu:   
                    system("clear");
                    printf("Menu\n\n");
                    break;  

                    default:
                    do{     
                            system("clear");
                            printf("Comando invalido!\n\nDigite:\n[1] Para acessar o menu\n[0] Para sair do programa\n\n>>> ");
                            scanf("%i", &p1);
                    }while (p1!=0 && p1!=1); 

                    if (p1==0){
                            goto exit;
                    }
                    if (p1==1) {
                            goto menu;
                    }

            }
    }

1 answer

2

The use of goto is a bad idea. Just use a repeat loop.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int p1, s2, s3;
    do {
        system("clear");
        printf("Digite:\n[1] Para acessar o menu\n[0] Para sair do programa\n\n>>> ");
        scanf("%i", &p1);
        switch (p1)
        {       
            case 0:
                system("clear");
                printf("Saindo\n\n");
                break;  
            //Pagina do Menu
            case 1: 
                system("clear");
                printf("Menu\n\n");
                break;  
            default:
                printf("Comando invalido!\n");
        }
    } while (p1 != 0);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.