← Back to C Course | Chapter 2: Input & Output | Lesson 7 of 7

C Input Validation

Input validation means checking that what a person typed is what you expected, like a doorman checking tickets. It stops your program from breaking on bad input.
Syntax
c
if (scanf("%specifier", &variable_name) == 1) {
  // input was valid
} else {
  // input failed
}

Why Unchecked scanf Is Dangerous

scanf returns the number of items it successfully read, but that return value is easy to ignore -- if a user types letters where a number is expected, the read fails, the target variable is left with whatever garbage it had before, and the program keeps running on bad data.

Example: Why Unchecked scanf Is Dangerous

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	int x;
	// Declare result and set it to sscanf("abc", "%d", &x)
	int result = sscanf("abc", "%d", &x);
	// Print formatted text to the screen
	printf("%d", result);
	// Return 0 to signal that the program finished successfully
	return 0;
}

Checking the Return Value

Comparing scanf's return value against the number of conversions you requested -- if (scanf("%d", &x) == 1) -- is the first line of defense, letting you detect a failed read immediately instead of silently trusting an uninitialized variable.

Example: Checking the Return Value

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	int x;
	// Check whether sscanf("42", "%d", &x) == 1
	if (sscanf("42", "%d", &x) == 1) {
		// Print formatted text to the screen
		printf("%d", x);
	} else {
		// Print formatted text to the screen
		printf("Invalid input");
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Clearing the Input Buffer

When scanf fails to match a number, the invalid characters are left sitting in the input buffer and will immediately cause the next read to fail too, so a failed scan should be followed by discarding characters up to the next newline before retrying.

Example: Clearing the Input Buffer

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	int x;
	// Check whether sscanf("abc", "%d", &x) != 1
	if (sscanf("abc", "%d", &x) != 1) {
		// Print formatted text to the screen
		printf("Discarded invalid input");
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Validating Ranges After a Successful Read

A successful scanf only confirms the input had the right format, not that the value makes sense -- a menu that reads an option number still needs a separate range check to reject an out-of-bounds choice like 99 on a 5-item menu.

Example: Validating Ranges After a Successful Read

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	int choice;
	sscanf("7", "%d", &choice);
	// Check whether choice >= 1 && choice <= 5
	if (choice >= 1 && choice <= 5) {
		// Print formatted text to the screen
		printf("Valid choice");
	} else {
		// Print formatted text to the screen
		printf("Out of range");
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Safer Alternatives for Line-Based Input

Reading a whole line with fgets into a buffer and then parsing it explicitly (with sscanf or strtol) gives you more control than scanf alone, since you can inspect the raw input before deciding how to interpret it, and it naturally avoids scanf's dangling-buffer problem.

Example: Safer Alternatives for Line-Based Input

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	char line[20] = "42\n";
	// Declare value and set it to strtol(line, NULL, 10)
	int value = strtol(line, NULL, 10);
	// Print formatted text to the screen
	printf("%d", value);
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Ignoring the return value of scanf, so bad input is treated as valid.
  2. Not clearing the input buffer after a failed read, causing an infinite loop.
  3. Checking only that the read succeeded, and forgetting to check that the value is in the allowed range.
Chapter Summary
  • Output in C is done with printf(), puts(), newlines, and escape sequences that control how text appears.
  • Input is read with scanf() and gets(), and format specifiers tell C how to interpret each value.
  • Input validation checks user data before your program relies on it.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.