Check if the input is an integer

Asked

Viewed 3,275 times

2

I need a function that reads a keyboard input 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. Besides, there is also a problem with printing. The printf runs the number of times the user has typed an invalid character. From now on, thank you for your patience.

Examples of Input and Output:

Input 15 Output Return 15;

Input -5 Exit Return -5;

Entry 0 Exit Return 0;

Input asefga*/+. Output Printf("Invalid Number") scanf Again;

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

Basically, the scanf must return any int, and continue 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;
}
  • tried creating a Try/catch block?

  • Sorry, but I haven’t gotten to that yet. I started ADS a little while ago, I’m on pointers.

  • @Walterfelipe in c?

  • Roberto, could for example how should be the inputs and outputs?

  • @Jeffersonquesado Ex: Input 15 Output Return 15; //Input -5 Output Return -5; //Input 0 Output Return 0; //Input asefga*/+. Output Printf("Invalid Number") scanf Again; //Input sdasddddas55546 Output Printf("Invalid Number") scanf Again; // Gave understanding?

  • @Robertokennedy put in the text of the question

  • @Jeffersonquesado Oh, okay

  • 1

    You’re wanting a function that determines whether the input has just numbers, that’s it?

  • @Pabloalmeida Almost this, the function should return only numbers, yes. While the user type any type of char, the do while should repeat itself. My current function, is accepting when the user type letter and number together, canceling all chars and putting in the variable the numbers; I need this function Enter "invalid number" while characters are being typed;

  • And if the number has two digits?

  • @Pabloalmeida, can also accept any int, with one or ten digits, be it positive or negative;

  • Got it. I’ll write the answer here.

  • Thank you! I’m waiting

  • No attempt with regular expressions yet?

Show 9 more comments

1 answer

3


The problem here is that you’re using scanf, who’s interpreting the entry as an indepentende number of what’s really there. What you can do is read your input as text and then use the function strtol in your input. This function already does both: converts to number and reports 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 necessary. You may also want to place more validations if the person type a number larger than the size of the long. Behold Documentation of the function for more details.

  • 2

    Elegant. Only the last semicolon at the end of the function block lerApenasSeForInteiro that is unnecessary

  • 2

    I don’t even know how he got there. I’m gonna take. :)

  • @Pabloalmeida, first of all thank you for your attention, but the test still contains some flaws. The most critical is when the user type number and letters. Your program works well, if the letter is typed first, however, when typing Ex:"123abc", she does the same as mine, ignores the char and picks up the number. Hugs

  • 1

    You’re right, @Robertokennedy. I had tested only with letters followed by numbers. Now it’s settled to "123abc" as well. See the change in if and the explanation in the comment.

  • @Pabloalmeida, Genial! Thank you very much!

Browser other questions tagged

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