Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Type Conversion C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Pass By Reference C Scope C Function Declaration C Functions Challenge C Math Functions C Inline Functions C Recursion C Function Pointers

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Structs Challenge C Nested Structures C Arrays of Structs C Structs & Pointers C Unions C typedef C Struct Padding

C Enums

C Enums

C Memory

C Memory Management C Allocate Memory C Access Memory C Reallocate Memory C Deallocate Memory C Structs and Memory C Memory Example C Memory Mistakes

C Errors

C Errors C Error Challenge C Debugging C NULL C Error Handling C Input Validation

C Problem Solving

C Problem Solving C Build the Logic C Edge Cases & Errors C Test Cases

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers C Command-Line Args

C DSA

C DSA Intro C Searching C Sorting C Stacks C Queues C Linked Lists C Trees C Hash Tables C Big O

C Projects

C Projects

C Cert

C Certificate

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A

C Input Validation


Share

Input Validation

When users enter data into a C program, they might type something unexpected. Input validation makes sure the input is correct before the program continues.

Without validation, your program might crash or give the wrong result!

The examples below show simple ways to check if the user's input is valid in C.


Validate Number Range

Check if the number is within an allowed range (for example, 1 to 5):

Example

#include <stdio.h>

int main() {
  int number = 0; // Variable to store the user's number

  do {
    printf("Choose a number between 1 and 5: ");
    scanf("%d", &number); // Read number input
    while (getchar() != '\n'); // Clear leftover characters from input buffer
  } while (number < 1 || number > 5); // Keep asking until number is between 1 and 5

  printf("You chose: %d\n", number); // Print the valid number
  return 0;
}

Example Result:

Choose a number between 1 and 5: 8
Choose a number between 1 and 5: -2
Choose a number between 1 and 5: 4
You chose: 4

The text the user types waits in the input buffer until the program reads it. scanf() only reads the number, and leaves the rest (like the Enter key, \n) in the buffer. The line while (getchar() != '\n'); reads the leftover characters one by one and throws them away, until it has read the \n.

This is important when the user types a letter: scanf() cannot read it as a number, so the letter stays in the buffer. Without the getchar() line, the next scanf() would try to read the same letter again, and the loop would never end.


Validate Text Input

Check that a name is not empty. Use fgets() and check the first character:

Example

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

int main() {
  char name[100]; // Buffer to store the user's name

  do {
    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin); // Read input as a string
    name[strcspn(name, "\n")] = '\0'; // Remove the newline character if present
  } while (strlen(name) == 0); // Repeat if the input is empty

  printf("Hello, %s\n", name); // Greet the user
  return 0;
}

Example Result:

Enter your name:
Enter your name:
Enter your name: John
Hello, John

fgets() also stores the Enter key as a newline character (\n) at the end of the text. The line name[strcspn(name, "\n")] = '\0'; finds the \n and replaces it with '\0' (the null character that ends a string). If the user only presses Enter, the name is now empty (strlen(name) is 0), so the loop asks again.



Validate Integer Input

Make sure the user enters a number. If they enter something else (like a letter), ask again using fgets() and sscanf():

Example

#include <stdio.h>

int main() {
  int number;       // Variable to store the user's number
  char input[100];  // Buffer to hold user input as a string

  printf("Enter a number: ");

  // Keep reading input until the user enters a valid integer
  while (fgets(input, sizeof(input), stdin)) {
    // Try to read an integer from the input string
    if (sscanf(input, "%d", &number) == 1) {
      break; // Success: break out of the loop
    } else {
      printf("Invalid input. Try again: "); // If not an integer, ask again
    }
  }

  // Print the valid number entered by the user
  printf("You entered: %d\n", number);
  return 0;
}

Example Result:

Enter a number: AB
Invalid input. Try again: hello
Invalid input. Try again: 35
You entered: 35

fgets() reads the whole line, so nothing is left in the input buffer, and you do not need the getchar() line from the first example. Then sscanf() tries to read a number from the text. It returns how many values it could read, so if it returns 1, the user entered a number.

Note: sscanf() reads the number at the start of the input. If the user types 3.5, it reads 3 and accepts it.

Tip: You can read more about fgets() and sscanf() in our <stdio.h> library reference.


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.