Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input validation using scanf() [duplicate]

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?

like image 942
Matthew Avatar asked Mar 05 '13 15:03

Matthew


2 Answers

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.

like image 141
md5 Avatar answered Oct 06 '22 12:10

md5


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);
like image 36
John Bode Avatar answered Oct 06 '22 11:10

John Bode