Scanf is not stopping in repetition

3

I have a loop while that will only end when the value 0 (zero) is entered. I have a variable that will receive a command option. Within the loop I have a switch case where:

  • 0) exits the program (returns to while and ends);
  • 1) asks for a letter to be written;
  • 2) shows the written lyrics.

Well, the problem is actually case 1 . Here is the code:

file: teste_while_e_switch.c

#include <stdio.h>

int main()
{
  int op=-1;
  char letra=' ';

  while(op!=0){
      printf("\n0) sair\
      \n1) digite uma letra\
      \n2) mostre a letra\
      \nOp: ");
      scanf("%d", &op);

      switch(op){
          case 0: { break; }
          case 1: { printf("letra: "); scanf("%c", &letra); break; }
          default:{ printf("opcao invalida.\n"); break; }
      }
  }
  printf("fim");
  return 0;
}

When running the program, it behaves like this:

0) sair
1) digite uma letra
2) mostre a letra
Op: 1
letra:
0) sair
1) digite uma letra
2) mostre a letra
Op:

As far as my understanding goes, the loop should show the message of op , wait until I type a letter and then follow the code again showing the menu. >     

asked by anonymous 25.01.2016 / 13:38

1 answer

6

I decided to respond to give a code cleaner and within the standards:

#include <stdio.h>

int main() {
    char op = ' ';
    char letra = ' ';
    do {
        printf("\n0) Sair\
            \n1) Digite uma letra\
            \n2) Mostre a letra\
            \nOp: ");
        scanf(" %c", &op);

        switch (op) {
            case '0':
                break;
            case '1':
                printf("\nLetra: ");
                scanf(" %c", &letra);
                break;
            case '2':
                printf("\nLetra digitada: %c", letra);
                break;
            default:
                printf("\nOpcao invalida.");
        }
    } while (op != '0');
    printf("fim");
    return 0;
}

See working on ideone .

There's still some bad logic in it, but for an exercise it's fine.

Using fgets() is still more recommended than scanf() that can be used on things simple as that.

If you want to get rid of ENTER you can do this:

#include <stdio.h>

int main() {
    char op = ' ';
    char letra = ' ';
    do {
        printf("\n0) Sair\
            \n1) Digite uma letra\
            \n2) Mostre a letra\
            \nOp: ");
        op = getchar();

        switch (op) {
            case '0':
                break;
            case '1':
                printf("\nLetra: ");
                letra = getchar();
                break;
            case '2':
                printf("\nLetra digitada: %c", letra);
                break;
            default:
                printf("\nOpcao invalida.");
        }
    } while (op != '0');
    printf("fim");
    return 0;
}

See working on ideone .

    
25.01.2016 / 14:25