C - Input Validation in c

1. Why Input Validation Matters in C

C reads input raw — meaning:

  • You can read too much into a buffer (buffer overflow)

  • You might get unexpected formats

  • Non-numeric input could break your calculations

  • Missing null terminators could corrupt strings

So, you must check:

  1. Is the input in the expected format?

  2. Is the input within safe limits?

  3. Is the buffer large enough?


2. Basic Tools for Input Validation

2.1 Safe Reading of Strings

Instead of:

scanf("%s", str); // unsafe — no size limit

Use:

scanf("%9s", str); // limit input length (for char str[10])

or better:

fgets(str, sizeof(str), stdin); // safe string input

Then strip newline:

str[strcspn(str, "\n")] = 0;

2.2 Validating Integers

Don’t assume the user typed an integer:

int num;
if (scanf("%d", &num) != 1) {
    printf("Invalid input!\n");
    while (getchar() != '\n'); // clear buffer
}

You can also read as a string and check manually with <ctype.h>:

#include <ctype.h>
#include <string.h>

int isInteger(const char *str) {
    if (*str == '-' || *str == '+') str++; // allow sign
    if (!*str) return 0; // empty string after sign
    while (*str) {
        if (!isdigit(*str)) return 0;
        str++;
    }
    return 1;
}

2.3 Validating Floating-Point Numbers

Same idea — check characters before using strtod():

#include <stdlib.h>

char input[50];
fgets(input, sizeof(input), stdin);
char *end;
double val = strtod(input, &end);
if (end == input || *end != '\n') {
    printf("Invalid float input!\n");
}

3. Range Checking

Even if the format is correct, check if the value is reasonable:

if (num < 0 || num > 100) {
    printf("Out of range!\n");
}

4. String Content Validation

Using <ctype.h>:

int isAlphabetic(const char *str) {
    while (*str) {
        if (!isalpha(*str)) return 0;
        str++;
    }
    return 1;
}

5. Example: Validating Age Input

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main() {
    char buf[10];
    int age;

    printf("Enter your age: ");
    fgets(buf, sizeof(buf), stdin);
    buf[strcspn(buf, "\n")] = 0;

    int valid = 1;
    for (int i = 0; buf[i]; i++) {
        if (!isdigit((unsigned char)buf[i])) {
            valid = 0;
            break;
        }
    }

    if (!valid) {
        printf("Invalid input. Only digits allowed.\n");
        return 1;
    }

    sscanf(buf, "%d", &age);
    if (age < 0 || age > 120) {
        printf("Age out of range.\n");
        return 1;
    }

    printf("Your age is %d.\n", age);
    return 0;
}

6. Best Practices for Input Validation in C

  • Always limit buffer sizes in scanf and fgets.

  • Prefer reading into a string and validating manually.

  • Use <ctype.h> for character checks.

  • Always clear leftover input from the buffer when validation fails.

  • Do range checks even after format checks.

  • Avoid gets() — it’s dangerous and removed from the C standard.

 

Do you want me to prepare that?