How do I validate input into c?

0

My problem is that I have to force the user to enter a single integer value, if he puts anything else (characters or decimals) I should have him type again. I already tried to validate scanf but it did not work. So I did a function to do the validation, but it did not work, so I took the function and left everything in main same and it is not working either, I have no ideas ...

So the code now, the program accuses any entry as invalid, even if it is an integer.

int maiorNumero(int,int);

int main()
{
    int a=0,b=0;
    int flag=0,maior=0;

do
{
    fflush(stdin);
    puts("Digite um numero inteiro:\n");
    scanf("%i",&a);
    puts("Digite um numero inteiro:\n");
    scanf("%i",&b);

    float f=a;
    float f2=b;
    char c=a;
    char c2=b;

    if(f!=a || f2!=b || c!=a || c2!=b)
    {
        flag=1;
        puts("Numero invalido!\nDigite apenas NUMEROS INTEIROS.\n");
    }
    else
    flag=0;

}while(flag==1);

maior=maiorNumero(a,b);
printf("O maior numero digitado foi: %i .",maior);

return 0;
}


int maiorNumero(int a, int b)
{
   int maior;

   if(a>b)
   {
      maior=a;
   }
   else
   if(a<b)
    {
        maior=b;
    }

return maior;
}

What am I missing? And if the number of variables (which is 2: a b ) is n where n is defined by the user, will I be able to use this logic or will I have to use validation by scanf ?

    
asked by anonymous 26.10.2016 / 00:30

2 answers

1

The best way to go is to analyze the input from a String (or vector of characters), so we can decide what is integer or not. It is important to note that C, to define the characters, uses the ASCII Table , that is , every character has an integer value and vice versa. We see in the table that the first number is '0' and that the last one is '9', so if the value that the user entered is less than '0' or greater than '9', we know that it is not a number. We also notice that the values in the Table are in ascending order, that is, if '0' = 48, '1' = 48 + 1 = 49, '5' = 48 + 5 = 53 and so on. With this in mind, we can convert from character to integer. I made a very simple function that returns NULL if its input contains something other than numbers:

int inteiro_validado(){
//Buffer para entrada da variável
char buffer[100];
//Ponteiro com endereco da String
char * entrada = gets(buffer);fflush(stdin); 
int i, resultado = 0, teste;
//Fazemos um loop para checar caractere por caractere da entrada
for(i = 0; i < strlen(entrada); i++){
    //Checa se é um numero
    if(entrada[i] >= '0' && entrada[i] <= '9'){
        //Se for, reduz da tabela ASCII
        teste = entrada[i] - '0';
        //Essa soma apenas coloca na casa decimal certa, se for 1024, ele vai fazer 1000 + 20 + 4
        resultado += teste * pow(10, strlen(entrada) - i - 1);
    }else{
        //A entrada contem um valor nao numérico
        return NULL;
    }
}

return resultado;

}

In order to apply this code it is very simple, just: int i = inteiro_validado() and check if i = NULL , if it is, your entry contains non-numeric characters.

Another tip is not to use %i for integer input, since %i allows the input of values in other bases supported by C, such as hexadecimal and octal. Use %d for decimal bases, %o for octal and %x for hexadecimal

    
26.10.2016 / 07:44
0

When you attempt to append a String value into an Integer , it will give memory error (Usually).

But if you read a String this is possible. Instead of using scanf("%i") and using scanf("%s") , you can use the atoi method to convert the value to integer (returns 0 if it is not a number).

Or check the characters inside String .

int x;
flag = 0;
for(x=0; x<strlen(a); x++){
    if(a[x] < '0' || a[x] > '9'){
        flag = 1;
        break;
    }
}
// O mesmo deve ser feito para b
    
26.10.2016 / 02:33