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?
– Walter Felipe
Sorry, but I haven’t gotten to that yet. I started ADS a little while ago, I’m on pointers.
– Roberto Kennedy
@Walterfelipe in c?
– Jefferson Quesado
Roberto, could for example how should be the inputs and outputs?
– Jefferson Quesado
@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?
– Roberto Kennedy
@Robertokennedy put in the text of the question
– Jefferson Quesado
@Jeffersonquesado Oh, okay
– Roberto Kennedy
You’re wanting a function that determines whether the input has just numbers, that’s it?
– Pablo Almeida
@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;
– Roberto Kennedy
And if the number has two digits?
– Pablo Almeida
@Pabloalmeida, can also accept any int, with one or ten digits, be it positive or negative;
– Roberto Kennedy
Got it. I’ll write the answer here.
– Pablo Almeida
Thank you! I’m waiting
– Roberto Kennedy
No attempt with regular expressions yet?
– Jefferson Quesado