Back to the beginning of the code after an if or switch case in C

3

I have a question regarding if .

I'm developing a college semester program and every time I need to use a if and at the end of if , I need to go back to the beginning of the program. I'm having a hard time doing this. Example: NOTE: The code below is illustrative, because mine is very large and I will not be able to post here.

char op;

print("Digite algo");
scanf("%s", &op);

if (op == "nome") {

//algo aqui

}

if (op == "telefone") {

//algo aqui

}

if (op != 'nome' && op != 'telefone') {

//queria colocar algo aqui que fizesse o usuario voltar ao começo do codigo e pedir o valor da op pra ele de novo.

}

This question is also related to switch case , where in default I wanted to put something like this (From back to the beginning of the code).

Can anyone help me understand?

    
asked by anonymous 25.11.2015 / 23:26

1 answer

4

You can use do-while . Until a valid option is entered, the program will continue to prompt you for input.

#include <stdio.h>

int main(void) {

    char op;

    do {      
         printf("Digite algo\n  0 - Sair\n  1 - Nome\n  2 - Telefone\n");

         scanf(" %c", &op);

         switch(op) {
               case '0': //sair
                   printf("Escolheu sair do menu\n");
                   break; 
               case '1': //nome
                   printf("Escolheu opção nome\n");
                   break;
               case '2': //telefone
                   printf("Escolheu opção telefone\n");  
                   break;
               default:
                   printf("Escolheu uma opção inválida\n");
                   break;
         }
    } while (op != '0');

    return 0;
}
    
25.11.2015 / 23:47