Return to code start after a C if or switch case

Asked

Viewed 12,863 times

3

I have a question regarding if.

I’m developing a program for the end of college semester and every time I need to use one if and at the end of if, I need you 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 too big 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.

}

That my doubt is also related to switch case, where in the default I wanted to put something in that style (From back to the beginning of the code).

Can someone help me understand?

  • Put the rest of the code to see where it has to go.

  • Your code has problems is storing a string on a char and checking strings with == will not work. In my opinion, could use goto wouldn’t hurt much legibility, or As @bigown has already said post the rest of the code.

  • Oh I got it. So my real code is very big, so I didn’t post it... That was a quick example of what I doubt. I should have specified that up there. : / I’ll edit. But thanks anyway. ;)

1 answer

4


You can use a do-while. Until a valid option is entered the program will continue to ask for user 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;
}
  • 1

    Ah, thank you. I’ll try to do it here with Do-While. ;)

Browser other questions tagged

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