Validation of scanf in c

Asked

Viewed 391 times

0

I have a problem that I need to validate an entry to receive only integers, if I do not receive, I must force the user to enter an integer. I cannot disregard numbers after the comma (in the case of decimals) and I cannot return the integer equivalent of a letter (in case the user informs letter).

    int lerInteiro();

    int main()
    {
        int numero=0;
        numero=lerInteiro();
        printf("Numero: %i .\n",numero);
        return 0;
    }


   int lerInteiro()
   {
       int numero=0;
       int flag=0;
       do
       { 
            fflush(stdin);
            puts("Digite um numero inteiro: \n");

            if(scanf("%i",&numero)!=EOF)
            {
                flag=1;
                puts("Numero invalido!\n");
                puts("Digite apenas NUMEROS\n!");
                puts("Digite apenas numeros INTEIROS!\n");
            }
            else
            flag=0;
        }while(flag==1);    
    return numero;
   }

The program must stop when an integer number is typed and return the typed number.

1 answer

4


Create a float variable and an integer to compare one to the other, that way.

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

    int lerInteiro();

    int main()
    {
        int numero=0;
        numero=lerInteiro();
        printf("Numero: %d .\n",numero);
        return 0;
    }


   int lerInteiro()
   {
       float numero=0;
       int flag=0;
       do
       { 
            fflush(stdin);
            puts("Digite um numero inteiro: \n");
            scanf("%f",&numero);
            int number = numero;
            if(number != numero)
            {
                flag=1;
                puts("Numero invalido!\n");
                puts("Digite apenas NUMEROS!\n");
                puts("Digite apenas numeros INTEIROS!\n");
            }
            else
            flag=0;
        }while(flag==1);    
    return numero;
   }
  • helped me, thanks, but what if the user type a letter, the same logic serves?

  • yes, you can test, the value assigned to the number will be different from the value in number and will enter in the same condition

Browser other questions tagged

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