Problem with switch case inside for loop

Asked

Viewed 62 times

-3

I need help with my code with switch case inside for loop.

I’m a beginner in programming and I don’t understand why the loop doesn’t run as desired. The desired would be to run the printfs before the switch and later the switch itself. Once the option inside the switch was chosen and everything inside it was run, the loop would start again. For some reason, it restarts but printfs before the switch appear more than once (once being the desired).

If anyone can tell me what I did wrong and what I can do to fix it I’d appreciate it.

#include <stdio.h>

int main(void) {
  char opcao;//opcao=a vista ou parcelado
  float trans, soma;//transações, soma=soma das trans
  int numt;//número de trasações

  trans = 0;
  soma = 0;

    for(numt=0;numt<15;numt++)/* Este loop é feito duas vezes seguidas sem chance de interação após a primeira entrada de dados, por algum motivo */
    {
      printf("\nEscolha umas das duas opções:");
      printf("\nv = transações à vista");
      printf("\np = transações a prazo");
      printf("\nDigite a sua escolha: ");
      scanf("%c", &opcao);
    
      switch(opcao)
      {
        case'v':
        printf("\nDigite uma transação: ");
        scanf("%f", &trans);
        soma = soma + trans;
        break;

        case'p':
        printf("");
        printf("\nDigite uma transação: ");
        break;

        default:
        printf("\nERRO! A opção deve ser 'v' ou 'p'. Reinicie o programa.");
      }

    }  
    
    printf("\nO valor das compras à vista é: %.2f", soma);
    printf("\nO valor total das compras");

  return 0;
}

1 answer

0


The problem is on the following line:

scanf("%c", &opcao);

What happens is that when we type some character in the terminal, in practice it is sent to the keyboard buffer (stdin), two characters:

  1. The character itself inserted.
  2. The character \n, generated by pressing the key Enter.

As you are reading only one character, the \n is still in the keyboard buffer, being read in the second loop iteration, skipping the second reading of the scanf() and falling into the default of your switch-case, which prints the error.

Then, when finished reading any data from the keyboard, using the scanf() or similar commands, the ideal is to always clean the buffer from the keyboard to remove the "data leftovers" from inside it. For this, you can put the function below above its function main():

void flush_buffer(){
    int c;
    while((c = getchar()) != '\n' && c != EOF)
    /* Descarta os demais caracteres do buffer */ ;
}

And call it within the function main(), after each scanf(), in the form below:

  scanf("%c", &opcao);
  flush_buffer();
  • 3

    https://stackoverflow.com/a/2979217

  • 3

    https://answall.com/a/325635/101

Browser other questions tagged

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