Force while loop output on C switch

Asked

Viewed 202 times

0

Guys, I made a menu in C language, but I need that when the user type option 4, it comes out of the repetition loop of/while, someone can help me. Thanks again to all for participating.

int opcao;

do
{
    menu();
    printf("\n");
    printf("Opção selecionada: ");
    scanf_s("%d", &opcao);

    switch (opcao)
    {
        case 1: adicionar();
            break;
        case 2: modificar();
            break;
        case 3: relatorio();
            break;
        case 4: Sair;
    }
} while ((opcao >= 1) && (opcao <=4));

2 answers

2

I think what you want is:

int opcao;
do {
    menu();
    printf("\nOpção selecionada: ");
    scanf_s("%d", &opcao);
    switch (opcao) {
        case 1: 
            adicionar();
            break;
        case 2: 
            modificar();
            break;
        case 3: 
            relatorio();
            break;
        case 4: 
            break;
        default:
            printf("\nOpção inválida");
    }
} while (opcao != 4);
  • Top, that’s exactly what I wanted to do thank you so much

1

If your code is inside a function, you could use return to get out, check it out:

void foobar(void) {
    int opcao;

    while(1) {
        menu();
        printf("\n");
        printf("Opção selecionada: ");
        scanf_s("%d", &opcao);

        switch (opcao) {
            case 1:
                adicionar();
                break;
            case 2:
                modificar();
                break;
            case 3:
                relatorio();
                break;
            case 4:
                return;
            default:
                printf("\nOpção inválida");
        }
    }
}

Browser other questions tagged

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