Verify that the entry is an integer

2

I need a function that reads a keyboard entry and validates whether it is an integer (negative or positive). If it is, it should return the value. Otherwise, it should report that the entry is invalid for the user and ask again.

The function I wrote validates this, however, it fails if the user reports characters mixed with numbers. Other than that, there is also a problem with printing. The printf runs the number of times the user typed an invalid character. Thanks in advance for your patience.

Input and Output Examples:

  

Input 15 Output Return 15;

     

Input -5 Output Return -5;

     

Input 0 Output Return 0;

     

Entry sets * / +. Output Printf ("Invalid Number") scanf Again;

     

Entry sdasddddas55546 Output Printf ("Invalid Number") scanf   Again;

Basically, the scanf should return any int , and continue the while while some char is typed;

int InserirValido(){

    int valor;
    int x=1;

    do
    {
        x =scanf("%d", &valor);
        getchar();

        if(x==0)
            printf("Numero Inválido");

    }while(x==0);

    return valor;
}
    
asked by anonymous 26.09.2017 / 23:09

1 answer

3

The problem here is that you are using scanf , which is interpreting the input as indepentende number of what actually has there. What you can do is read its input as text and then use the strtol function on its input. This function does both: convert to number and report errors. A code that does this would look like this:

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

long ler_apenas_se_for_inteiro();

int main() {
    printf("%ld", ler_apenas_se_for_inteiro());
    return 0;
}

long ler_apenas_se_for_inteiro(){
    char buffer_de_entrada[64];
    char* onde_a_funcao_de_conversao_parou;

    while (1) {
        fgets(buffer_de_entrada, 64, stdin);
        long numero_lido = strtol(buffer_de_entrada, &onde_a_funcao_de_conversao_parou, 0);

        /* Se o número resultante é zero e o ponteiro que aponta para o caractere da string
         * no final da conversão não andou é porque não ocorreu conversão, ou seja, falhou. Além disso, o caractere onde a conversão parou
         * tem que ser uma quebra de linha, caso contrário há caracteres não numéricos
         * que foram ignorados pelo strtol, o que significa que a entrada 
         * não possui somente números.
         */
        if ((numero_lido == 0 && onde_a_funcao_de_conversao_parou == buffer_de_entrada)
            || *onde_a_funcao_de_conversao_parou != '\n') {
            printf("Número inválido. Digite novamente.\n");
            continue;
        } else {
            return numero_lido;
        }
    }

}

The function is returning long . You can adapt convert to int if needed. You may also want to put more validations if the person types a number larger than the long size. See Function documentation for more details.

    
27.09.2017 / 00:04