Validating input with scanf ()

I have a program that takes an integer from a user and uses that number in an add operation.

The code I use to accept the number is as follows:

scanf("%d", &num);

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

+5
source share
2 answers

You must use the return value scanf. From man scanf:

Return value

These functions return the number of successfully inserted and assigned input elements, which may be less than provided, or even zero in case of an unsuccessful early match.

So it might look like this:

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

, " ". strtol, . .

+9

, scanf %s fgets, strtol, :

#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);
+1

All Articles