How do I validate input in c?

Asked

Viewed 5,595 times

1

My problem is that I have to force the user to enter a whole value only, if he puts anything else (characters or decimals) I have to make him type again. I’ve already tried to validate scanf but it didn’t work. So I did a function to do the validation, but it didn’t work, mainsame and also this not working out, I have no more ideas...

So this code now, the program accuses any input 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? What if the number of variables (which is 2:a b) for n where n is user-defined, I will be able to use this logic or I will have to use validation by scanf?

2 answers

1

The best way to go is to analyze the input from a String (or character array), so we can decide what is or is not integer. It is important to say 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 typed is less than '0' or greater than '9', we know that it is not a number. We also note 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 character to integer. I made a very simple function that returns NULL if its input contains anything 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;

}

To apply this code is very simple, just :int i = inteiro_validado() and check whether i = NULL, if it is, its entry contains non-numeric characters.

Another tip is not to use %i for whole input as %i allows input of values into other C-supported databases, such as hexadecimal and octal. Use %d to decimal bases, %o for octais and %x for hexadecimal

0

When you try to add a value String in a Integer, will give memory error(Normally).

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

Or check the characters inside the 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

Browser other questions tagged

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