Its function menu
must return an integer representing the chosen option, I did not see the return in your code. The function scanf
is problematic because it puts in the keyboard buffer the ENTER every time it is pressed, causing the loop when the input is not an integer.. It is right to always clean the buffer after reading with the scanf
, to avoid a headache.
To clear the buffer, use:
flush(stdin)
for Windows and __fpurge(stdin)
for Linux.
Use the function getchar()
also resolves, because she will capture the ENTER whenever you do reading, but it is best practice to clean the same buffer. I also recommend whenever you declare a variable, start it with some value, otherwise the C starts it with some random value (trash) which can also get in the way of comparisons/calculations etc.
I made some changes to the code, to be more "correct" so to speak:
#include <stdio.h>
#include <stdlib.h>
/*funcao menu, que retorna a opcao escolhida, ou -1 caso seja opcao invalida*/
int menu() {
int escolha=0;
printf("\n============== MENU ==============\n\n");
printf("Pressione 1 para ver as instrucoes\nPressione 2 para jogar\n");
/*aqui apos o scanf, uso a funcao logo em seguida para limpar o buffer,
no meu caso, testei no linux*/
scanf("%d",&escolha);
__fpurge(stdin);
/*flush(stdin)*/
/*getchar();*/
if (escolha==1)
return escolha;
else if (escolha==2)
return escolha;
else
return -1;
}
/*funcao so para testar uma opcao valida*/
void jogar(){
printf("JOGAR\n");
}
/*funcao so para testar uma opcao valida*/
void instrucoes(){
printf("INSTRUCOES\n");
}
/*funcao principal*/
int main(){
int escolha=0;
do{
escolha=menu();
switch (escolha){
case 1:
instrucoes();
break;
case 2:
jogar();
break;
default:
printf("Escolha inválida, tente novamente!");
break;
}
}while ((escolha < 0) || (escolha > 2));
return 0;
}
What does it mean to "enter a non-integer character"? With the format specified in your
scanf
your program only reads whole numbers.– anonimo
Any number or letter that is not integer. I know it only read integer, but not understanding why it gets in an infinite loop. From the moment I enter with an invalid number, the program rotates the loop endlessly over and over.
– Manrique Pereira
In this case it might be better for you to read as character and convert to integer when ensuring that the input is a digit.
– anonimo