codegurukool.com · Free coding tutorials & online compiler

Home › C Tutorial › C input validation

C input validation

Never trust input.

Check what scanf returns and range-check values before using them.

Example code

#include <stdio.h>
int main() {
  int n;
  if (scanf("%d", &n) != 1 || n < 1 || n > 10) {
    printf("Enter 1 to 10\n");
    return 1;
  }
  printf("OK %d\n", n);
  return 0;
}

Run this code in the online editor

← C NULL and errorsC date and time →