Validate input data types

2
#include<stdio.h>
#include<limits.h>

int main() {

    int num;
    printf("%d\n",__INT_MAX__); //2147483647 

    printf("Introduce un numero: ");
    scanf("%d",&num);

    printf("%d",num);

    return 0;
}   

If I enter more than the posive range of int 2147483647 for example 999999999999999999999 or if I enter letters instead of numbers it may stop working. How can I limit or validate this?

    
asked by WOLD26 17.05.2018 в 01:53
source

1 answer

2
  

int scanf(const char *format, ...)

From the definition of the function header set above we can deduce that the value returned by scanf can mean several things, including what the standard says:

  

7.21.6.4p3 : The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) you have completed. Otherwise, the scanf function returns the number of input items assigned, which can be less than provided for, or even zero, in the event of an early matching failure.

In summary, in Spanish: scanf can return EOF in case of error or the number of "parsed" arguments correctly; the same number can be zero.

Consider the code in your question:

scanf("%d",&num);

As a good practice, it is best to evaluate the result of that call:

if (scanf("%d", &num) == 1) {
  printf("%d fue leido correctamente!\n", num);
}
else printf("no pude leer la variable num.\n");

It is not absolutely necessary, but if you want to validate the input you read from the keyboard, you will need to do something similar; Another way to compare it is:

switch (scanf("%d", &num)) {
  case EOF: printf("Ha ocurrido un error interno.\n"); break;
  case 0: printf("No se han escaneado valores."); break;
  default: /* Haz algo para cada argumento. */ break;
}

And go adding the cases in which you need to compare.

  

A paragraph about it with scanf and integers: function scanf will not return an error value in case a value is greater than the range allowed by that data type, scanf will try parse it and then assign it, regardless of whether the destination type is large enough to store that value.

     

If you want to validate that a value fits within the range of a number, you will have to implement your own control, reading the characters by hand to then verify their value or with some other shape that comes to mind.

References:

Greetings:)

    
answered by 17.05.2018 / 04:35
source