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;
}