Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

C Tutorial

C HOMEC IntroC Get StartedC SyntaxC OutputC CommentsC VariablesC Data TypesC Type ConversionC ConstantsC OperatorsC BooleansC If...ElseC SwitchC While LoopC For LoopC Break/ContinueC ArraysC StringsC User InputC Memory AddressC Pointers

C Functions

C FunctionsC Function ParametersC ScopeC Function DeclarationC Math FunctionsC Inline FunctionsC RecursionC Function Pointers

C Files

C Create FilesC Write To FilesC Read Files

C Structures

C StructuresC Nested StructuresC Structs & PointersC UnionsC typedefC Struct Padding

C Enums

C Enums

C Memory

C Memory Management

C Errors

C ErrorsC DebuggingC NULLC Error HandlingC Input Validation

C More

C DateC Random NumbersC MacrosC Organize CodeC Storage ClassesC Bitwise OperatorsC Fixed-width Integers

C Projects

C Projects

C Reference

C ReferenceC KeywordsC <stdio.h>C <stdlib.h>C <string.h>C <math.h>C <ctype.h>C <time.h>

C Examples

C ExamplesC Real-Life ExamplesC ExercisesC QuizC CompilerC SyllabusC Study PlanC Interview Q&AC Certificate

CInput Validation


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; // 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

Validate Text Input

Check that a name is not empty. Usefgets() 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

Validate Integer Input

Make sure the user enters a number. If they enter something else (like a letter), ask again usingfgets() andsscanf():

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: 3.5
Invalid input. Try again: 35
You entered: 35

Tip: You can read more aboutfgets() andsscanf() in our<stdio.h> library reference.



×

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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2025 Movatter.jp