4
I have a loop while
which will only end when 0 (zero) is entered. I have a variable which will receive a command option. Inside the loop I own a switch
marry where:
- 0) exits the program (returns to while and ends);
- 1) requests that a letter be written;
- 2) shows the letter written.
Well, the problem is actually case 1
. Follow the code made:
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 as follows:
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 extends, loop should show the message of op
, wait until I typed a letter and only then follow the code showing again the menu.
This is the old problem of
scanf
. You can’t use it with impunity buffer.– Maniero
@Bigown would explain me better about this? And if possible a way to resolve this. Actually I can type the letter and it returns when I access option 2, however the loop goes on without waiting for me to type, so it seems that I am typing a new option and not the letter I would like.
– bruno101
I removed my comments because I hadn’t seen the problem at first. That’s exactly what @bigown said, problem with scanf. He’ll probably post an answer.
– cantoni
Related: http://answall.com/q/42981/101
– Maniero
First I would like to thank lvcs and bigown because they were the ones who were able to help me and understand the problem. For those with a problem similar to mine: Just adding a space before the formatting of the scanf was possible to solve, all the explanations in detail are in the comments and answers, plus other tips that may be useful for other cases.
– bruno101