Problem with scanf in %d receiving a keyboard letter

Asked

Viewed 268 times

0

I’m having a problem, I’m reading a int %d for scanf, but if the user type a letter the program enters loop.

void chama_menu_switch(Fila **f, int n){

char confi;
int i,y,x,a,z;
double r;
a = 0;
int b;
for (i = 0; z != 11; i++) { // inicio for

printf("|*|Comandos Menu 1.0|*|\n1 - Criar nova coluna\n2 - Deletar uma coluna\n3 - Inserir receita em coluna\n4 - Remover receita em coluna\n5 - Visualizar lista de colunas\n6 - Remover despesa em coluna\n7 - Inserir despesa em coluna\n8 - Visualiza despesas em uma coluna\n9 - Visualiza receitas em uma coluna\n10 - Calcular lucro bruto\n11 - Sair\n");
    //_flushall();
b = scanf("%d%*c",&z);
    __fpurge(stdin);
    fflush(stdout);
    if (b == 0) {
        printf("entro");
        system("pause");
        scanf(" %d",&b);
    }

I made a mini menu using switch on the console.. ta working normally, default on switch understands that this is not in the cases and the break, but he ignores the scanf and gets into loop.

1 answer

1

I structured my menus more or less in this way friend

int opcao;

do{
    printf("1- Opcao 1 \n2- Opcao 2 \n0- Sair");
    scanf("%d", &opcao);

    switch(opcao){
        case 1: printf("Opcao 1"); break;
        case 2: printf("Opcao 2"); break;
    }
}while(opcao != 0)
  • Felipe , I’m using a for because I’m passing values of the sums to a pointer vector for some structures.. but anyway if I use a do while if the user type a letter in your int will crash.. a friend of mine found the solution I will post here in case other people seek the same doubt, thank you very much.

  • Another solution was using a char as an option, in which case it would not crash.

  • Exactly, I did almost that. I passed for a char and dps converted to int.. I made a macumba here, I do not know if it is the most practical, maybe if I had done everything from the beginning for char I would have given less headache, but to change now for everything char would screw me. Position: http://pastebin.com/fHPV880q

  • Haha, I agree, I should have done everything with char '~'

Browser other questions tagged

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