Input validation using scanf()

30,188

Solution 1

You should use scanf return value. From man scanf:

Return Value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

So it may look like this:

if (scanf("%d", &num) != 1)
{
    /* Display error message. */
}

Notice it doesn't work for "numbers with the decimal point". For this you should rather use parsing and strtol for instance. It may be a bit more complex.

Solution 2

Read your input as text using either scanf with a %s conversion specifier or by using fgets, then use the strtol library function to do the conversion:

#define MAX_DIGITS 20 // maximum number of decimal digits in a 64-bit integer

int val;
int okay = 0;

do
{
  char input[MAX_DIGITS+2]; // +1 for sign, +1 for 0 terminator
  printf("Gimme a number: ");
  fflush(stdout);
  if (fgets(input, sizeof input, stdin))
  {
    char *chk = NULL; // points to the first character *not* converted by strtol
    val = (int) strtol(input, &chk, 10);
    if (isspace(*chk) || *chk == 0)
    {
      // input was a valid integer string, we're done
      okay = 1;
    }
    else
    {
      printf("\"%s\" is not a valid integer string, try again.\n", input);
    }
  }
} while (!okay);
Share:
30,188
Matthew
Author by

Matthew

Updated on March 06, 2020

Comments

  • Matthew
    Matthew about 4 years

    I have a program which accepts an integer from the user and uses this number in an addition operation.

    The code which I am using to accept the number is this:

    scanf("%d", &num);
    

    How can I validate the input such that if the user enters a letter or a number with the decimal point, an error message is displayed on the screen?

  • Matthew
    Matthew about 11 years
    I was going to tell you about the decimal numbers part. I'll check how the strtol function works. Thanks
  • Matthew
    Matthew about 11 years
    So there's no way to catch such a situation in C? For instance, in Java an exception is raised if a float is presented to an integer variable.
  • teppic
    teppic about 11 years
    @Matthew The problem is that scanf won't read it as a float, it'll read it as an integer followed by a non-integer (the '.'), because you've told it an integer is expected.