Block letters and special characters

0

Good afternoon. I'm developing a C program and I have to deal with it when the user types letters or special characters. It turns out that when I try to type a letter, the program will loop, type flashing on the screen. I wanted to know how I handle this. Thanks

int main(){
int opcao_menu;
while(opcao_menu != 5){
printf("\nEscolha sua opção:\n\n\n
        1 - ...\n
        2 - ...\n
        3 - ...\n
         printf...
         printf("\n\n5 - Sair");
         printf("\n\n\nSua escolha: ");
         scanf("%d", &opcao_menu);
system("cls");
            printf("Opcao invalida!\n");
    }
    return 0;
}
    
asked by anonymous 11.05.2017 / 19:25

2 answers

2

The truth is that while practice has shown that the printf() function is very useful for multiple purposes, unfortunately the scanf() function is not that useful. In particular, it does not handle as well as expected non-standard inputs, as you could verify.

In this case, the default recommendation of experienced C users is to get the entire row for a buffer using fgets() ( never gets() ) and then parse the input, possibly using sscanf() to do so. For example:

int
main(int argc, char ** argv) {
    static char buffer[1024];
    int opcao_menu = 0;

    while (opcao_menu != 5) {
        // Literais de string uma após a outra são concatenadas
        // Útil para escrever strings longas
        fputs("\nEscolha sua opção\n\n\n"
              "1 - ...\n"
              "2 - ...\n"
              "3 - ...\n"
              "4 - ...\n"
              "5 - Sair\n"
              "\n\nSua escolha: ", stdout);
        // Obtém a linha que o usuário digitou até o [Enter]
        fgets(buffer, sizeof(buffer), stdin);
        // Tenta extrair um número do buffer e verifica os limites do número
        if ((sscanf(buffer, "%d", &opcao_menu) < 1) ||
            (opcao_menu < 1) ||
            (opcao_menu > 5)) {
            system("cls");
            fputs("Opção inválida!\n", stdout);
        } else switch (opcao_menu) {
            // Aqui tratamos os diferentes casos,
            // tipicamente chamando uma função para fazê-lo
            case 1: do_1(); break;
            case 2: do_2(); break;
            case 3: do_3(); break;
            case 4: do_4(); break;
            case 5: fputs("Até mais!\n", stdout); break;
        }
    }

    return 0;
}
    
11.05.2017 / 20:01
1

Try to validate if the input size exceeds what is allowed, which is 1 digit, taking the size with a function, or if the first pos is not a digit.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int tam(char *s) {
    int cont = 0;
    while(*s++) {
        ++cont;
    }
    return cont;
}

int main()
{

    char opc[1024];

    do {

        printf("\nEscolha uma opcao\n");
        printf("0: Sair\n");
        printf("1: Exibir msg 1\n");
        printf("2: Exibir msg 2\n");
        printf("Opcao: ");
        fgets(opc, sizeof(opc), stdin);
        opc[tam(opc) - 1] = 0;
        if(!isdigit(opc[0]) || tam(opc) > 1) {
            printf("Entre com um digito entre 0 e 2\n");
        }

        else {
        int numero = atoi(opc);
        switch(numero) {
            case 0: exit(0);
            case 1:
                puts("Ola");
                break;
            case 2:
                puts("Oi");
                break;
            default:
                printf("Opcao Invalido\n");
                break;
        }
      }
    }while(1);

    return 0;
}
    
11.05.2017 / 21:11