Validate a type of data when reading it in C

0

I would like to know the best and most efficient way to read a type of data and if you type anything else that does not pass from there, until you type the type of data that I am asking for.

Example:

int numero;
printf("Digite un numero: ");
scanf("%d",&numero);

If the user types a letter, that does not accept it; if the user types in signs such as:., '{[]}] # € ~ €€ ~~ @ # @ | among others, that does not accept it; the same goes for the data type char , which I could not control very well because it accepts numbers and signs.

What I'm looking for is that the data reading is fairly compact and secure.

I am implementing the following statement to read a specific data type but I need you not to accept the signs: .'{{{{{{{{# | € @ # € '%%% of ++', etc .

      do //Utilizo un 'do-while' para validar el ingreso del tipo de dato.
    {       
        system("CLS");  
        printf("DIGITE EL NUMERO DE CONJUNTOS QUE DESEA CREAR (DEBE SER MAYOR A '0' - HASTA 20 ): ");
    }
    while(!scanf("%d",&vectores)==1 || vectores==0 || vectores>20);

As long as scanf does not return 0, it will continue there; I do not know if it's the best way but it works very well since it's the shortest sentence I've seen to validate a type of data.

    
asked by LordOfDreams 08.05.2018 в 03:12
source

3 answers

0

I used the function isalpha and isdigit of the library <ctype.h> to validate the type of data.

    
answered by 11.05.2018 / 23:11
source
2

You must capture a character and check if the character corresponds to a number, otherwise you can create a character string and check digit by digit:

do{
    char numero;
    printf("Digite un numero: ");
    scanf("%c",&numero);
while(numero<'0'||numero>'9');
int numero2=atoi(numero);

In the example of character strings you must loop with the string to check digit by digit.

    
answered by 09.05.2018 в 18:40
1

Look, to validate different types of data there are usually different validations, so I will limit myself to the second condition that is in your question

  

MUST BE GREATER TO '0' - UP TO 20

Which in fact is quite simple:

//buffer de lectura
char buffer[3];
//numero leido
int  n;
//Limpiamos el buffer
memset(buffer,0,3);
//Leemos exactamente dos caracteres del standar input
fread(buffer, 2, 1, stdin);
//Los convertimos a entero
n = atoi(buffer);
//Comprobamos el numero
if(n > 0 && n < 21){
    printf("OK");
}else{
    printf("NO");
}
    
answered by 09.05.2018 в 20:17