Handling user input in C is one of the first skills you need as a C programmer. Without it, your programs do the same thing every time they run. In this guide you’ll learn how to read numbers with scanf(), read text safely with fgets(), avoid the most common mistakes, and check what users type before you use it.

The Basics of User Input in C

When you first learn about user input in C, the most common function you will encounter is scanf(). This function reads formatted input from the standard input stream (usually the keyboard).

Here is a basic example of how to use scanf() to capture an integer:

#include <stdio.h>  int main() { int age; printf("Please enter your age: "); scanf("%d", &age); printf("You are %d years old.\n", age); return 0; } 

Handling String Input Safely

If you want to capture a full sentence or a string with spaces as user input in C, scanf() often falls short because it stops reading at the first whitespace. Instead, programmers should use fgets().

The fgets() function reads a line of text and stores it into a string buffer. It is much safer because it prevents buffer overflow errors by limiting the number of characters read.

#include <stdio.h>  int main() { char name[50]; printf("Enter your full name: "); fgets(name, sizeof(name), stdin); printf("Hello, %s", name); return 0; } 

Common Mistakes When Handling User Input in C

When working with user input in C, beginners often run into a few common errors. To ensure your programs run smoothly, keep these tips in mind:

  • Forgetting the Ampersand (&): When using scanf() for primitive data types like integers or floats, you must pass the memory address using &. Forgetting this will crash your program.

  • Buffer Overflow: Never use gets() to capture strings. It does not check the length of the input, which can overwrite memory. Always use fgets().

  • Newline Characters: fgets() captures the “Enter” key press (newline character) as part of the string. You often need to manually strip this character out of your final string.

How to Remove the Newline from fgets()

Because fgets() keeps the Enter key as \n at the end of the string, printing the name in the middle of a sentence breaks the line in the wrong place. The strcspn() function from <string.h> finds the position of the newline, and you can replace it with the end-of-string character '\0':

#include <stdio.h> #include <string.h>  int main() { char name[50]; printf("Enter your full name: "); if (fgets(name, sizeof(name), stdin) != NULL) { name[strcspn(name, "\n")] = '\0'; // replace the newline with the end of the string printf("Hello, %s! Nice to meet you.\n", name); } return 0; } 

If the user presses Enter without typing anything, strcspn() returns 0 and the string simply becomes empty, so this line is safe to use every time.

How to Validate User Input in C

A professional program never blindly trusts user input in C. If a user types a letter when your program expects a number, it can cause an infinite loop or a crash.

Always validate your input. You can check the return value of scanf() to ensure it successfully read the expected number of items. If it returns 0, the input was invalid, and you should clear the input buffer before asking the user to try again.

Here is what that looks like in practice. The program keeps asking until the user types a valid number:

#include <stdio.h>  int main() { int age; int result; int c; printf("Please enter your age: "); while ((result = scanf("%d", &age)) != 1) { if (result == EOF) { return 1; // no more input, so stop } while ((c = getchar()) != '\n' && c != EOF) { // throw away the rest of the bad line } printf("That's not a number. Please enter your age: "); } printf("You are %d years old.\n", age); return 0; } 

scanf() returns the number of values it read. When the user types letters, it returns 0 and leaves those letters waiting in the input buffer. The inner loop reads and discards them up to the end of the line, so the next scanf() starts fresh. If the input ends completely (EOF), the program stops instead of looping forever.

For more detail on reading input safely, see the fgets documentation.

New to C? Start with my Introduction to C programming guide to learn about variables and data types.

Let’s put this into practice with a small program that asks for two numbers.

Practice Example: Area of a Rectangle

// calculating the area of a rectangle using user input #include <stdio.h>  int main() { int length; int width; printf("Enter the length of the rectangle: "); scanf("%d", &length); printf("Enter the width of the rectangle: "); scanf("%d", &width); int area = length * width; printf("\n"); printf("The area of the rectangle is %d cm^2\n", area); return 0; } 

Here is how the program works, line by line. The comment at the top, // calculating the area of a rectangle using user input, tells anyone reading the code what the program does.

#include <stdio.h> loads the standard input/output library, which gives you printf() and scanf().

int main() { ... } is where the program starts running.

int length; and int width; declare two integer variables to hold the whole numbers the user types.

printf shows a prompt asking for the length.

scanf("%d", &length); reads the number the user types and stores it at the memory address of length. That’s why the & is needed.

The same two steps then ask for the width and store it.

int area = length * width; multiplies the two numbers and saves the result in a new variable called area.

printf("\n"); prints an empty line so the result is easier to read.

The last printf prints the area, replacing %d with the value of area and adding “cm^2” as the unit. Here is the output when you enter 5 for the length and 4 for the width:

Terminal output of the C rectangle program: length 5 and width 4 give an area of 20 cm^2

Try this next: the program happily accepts letters and negative numbers. Add the validation loop from earlier to reject bad input, or switch the variables to double (read them with %lf and print the area with %.2f) so it can handle measurements like 2.5.

Practice Example: Area of a Circle

// calculating the area of a circle // formula is A = π * r^2 #define _USE_MATH_DEFINES // needed for M_PI with MSVC (cl.exe) #include <math.h> #include <stdio.h>  int main() { int radius; printf("Enter the radius of the circle: "); scanf("%d", &radius); double area = M_PI * radius * radius; printf("The area of the circle is %.2f cm^2\n", area); return 0; } 

This program asks for a radius and prints the area of the circle. It uses the same scanf() pattern as the rectangle example, plus one new tool: the math library.

How the Code Works

  • #define _USE_MATH_DEFINES turns on math constants like M_PI in Microsoft’s compiler. GCC and Clang usually provide them anyway, so the line is harmless there.

  • #include <math.h> gives you M_PI, which holds π (about 3.14159).

  • int radius; creates a whole-number variable. Then scanf("%d", &radius); stores the user’s number in it. The & passes the variable’s address, so scanf knows where to write.

  • double area = M_PI * radius * radius; applies the formula A = π × r². The result is a double because π has decimals.

  • %.2f prints the area rounded to two decimal places.

For example, a radius of 5 prints “The area of the circle is 78.54 cm^2”.

Terminal output of the C circle program: radius 5 gives an area of 78.54 cm^2

Two Things to Watch

First, the radius is an int. If the user types 2.5, scanf reads only the 2 and stops at the dot. As a result, the program quietly prints the area for a radius of 2 (12.57) instead of 19.63.

Second, nothing checks the input. If the user types a letter, scanf reads nothing, so radius keeps a random leftover value. In one test, typing abc printed 82447.96. That’s exactly why validating user input in C matters.

To fix both, read the radius as a double with %lf, and check that scanf returns 1, just like in the validation section above:

double radius; printf("Enter the radius of the circle: "); if (scanf("%lf", &radius) != 1 || radius < 0) { printf("Please enter a positive number.\n"); return 1; } 

Now 2.5 gives the correct area of 19.63, and letters or negative numbers get a clear message.

Practice: the circumference of a circle uses a different formula, C = 2 × π × r. Try adding it to the program so it prints both values.

Making Decisions with User Input: if else in C

Reading input is only half the job. Once your program has the user’s answer, it usually needs to decide what to do next. That’s where if and else come in.

An if statement runs a block of code only when its condition is true. The else block runs when the condition is false. For example, this program reads a number and tells you whether it’s even or odd:

#include <stdio.h>  int main(void) { int number; printf("Enter a whole number: "); if (scanf("%d", &number) != 1) { printf("That's not a number.\n"); return 1; } if (number % 2 == 0) { printf("%d is even.\n", number); } else { printf("%d is odd.\n", number); } return 0; } 

Here, number % 2 gives the remainder after dividing by 2. If the remainder is 0, the number is even. Otherwise, the else block reports that it’s odd. Notice that the program checks what scanf() returns first, so typing a letter can’t break it.

Comparison Operators

Conditions usually compare two values. These are the operators you’ll use most:

  • == equal to, and != not equal to

  • > greater than, and < less than

  • >= greater than or equal to, and <= less than or equal to

  • && true when both conditions are true

  • || true when at least one condition is true

Checking Several Conditions with else if

Sometimes there are more than two possible answers. In that case, chain the conditions with else if. C checks them from top to bottom and runs the first block that matches. This grade checker shows how it works:

#include <stdio.h>  int main(void) { int score; printf("Enter your score (0-100): "); if (scanf("%d", &score) != 1 || score < 0 || score > 100) { printf("Please enter a number from 0 to 100.\n"); return 1; } if (score >= 90) { printf("Grade: A+\n"); } else if (score >= 85) { printf("Grade: A\n"); } else if (score >= 80) { printf("Grade: A-\n"); } else if (score >= 77) { printf("Grade: B+\n"); } else if (score >= 73) { printf("Grade: B\n"); } else if (score >= 70) { printf("Grade: B-\n"); } else if (score >= 67) { printf("Grade: C+\n"); } else if (score >= 63) { printf("Grade: C\n"); } else if (score >= 60) { printf("Grade: C-\n"); } else if (score >= 57) { printf("Grade: D+\n"); } else if (score >= 53) { printf("Grade: D\n"); } else if (score >= 50) { printf("Grade: D-\n"); } else { printf("Grade: F\n"); } return 0; } 

Because the checks run in order, a score of 82 fails the first two tests. However, it passes score >= 80, so the program prints A-. That’s also why the conditions go from the highest grade down: if score >= 50 came first, every passing score would print D-.

The first if uses || to reject anything outside 0 to 100, so impossible scores never reach the grading logic. The grade bands follow the common Ontario percentage scale (A+ is 90 and up), so change the numbers if your school uses a different one.

Terminal output of the C grade checker: a score of 100 prints Grade: A+

A Common Mistake: = Instead of ==

One equals sign assigns a value, while two equals signs compare values. So if (score = 100) doesn’t check the score at all. Instead, it sets the score to 100, and the condition is always true.

if (score = 100) { /* wrong: sets score to 100 */ if (score == 100) { /* right: compares score with 100 */ 

Luckily, GCC warns you about this when you compile with gcc -Wall. That’s one more reason to always turn warnings on.

Conclusion

Handling user input in C well is what turns a fixed script into a program people can actually use. Use scanf() for simple numbers, fgets() for text, and always check what the user typed before you trust it. Then use if and else to decide what to do with the answer. As a next exercise, add validation to the rectangle program above, and use an if statement to reject lengths that are zero or negative.

Keep learning: Introduction to C programming · Python For Beginners

Voting Age

#include <stdio.h>  int main (void) { int age; printf("Please enter your age: "); scanf("%d", &age); if (age >= 18){ printf("You are eligible to vote\n"); } else { printf("You are not eligible to vote\n"); } return 0; } 

1. Library Inclusion

  • #include <stdio.h>: This includes the Standard Input/Output library, which gives your program the ability to use input and output functions like printf and scanf.

2. The Main Function

  • int main (void): This is the entry point of every C program. Execution starts here. The int means it returns an integer value, and void indicates that the function takes no arguments.

3. Variable Declaration & Input

  • int age;: Declares an integer variable named age to store the user’s input.

  • printf("Please enter your age: ");: Prints the prompt message to the console so the user knows what to type.

  • scanf("%d", &age);: Reads an integer (%d) entered by the user from the keyboard and saves it into the memory location of the age variable (&age).

4. Conditional Logic (Decision Making)

  • if (age >= 18): Checks if the stored age is greater than or equal to $18$.

If true, it runs printf("You are eligible to vote\n");.

  • else: If the condition is false (the age is less than $18$), it runs the alternative block: printf("You are not eligible to vote\n");.

5. Program Exit

  • return 0;: Tells the operating system that the program has finished executing successfully.

BMI Calculator

 int main (void){ float weight; float height; printf("Please enter your weight in kg: "); scanf("%f", &weight); printf("Please enter your height in cm: "); scanf("%f", &height); height = height / 100; float bmi = weight / (height * height); printf("Your BMI is %.1f\n", bmi); if (bmi < 16) { printf("You are in Severe Thinness class\n"); } else if (bmi < 17) { printf("You are in Moderate Thinness class\n"); } else if (bmi < 18.5) { printf("You are in Mild Thinness class\n"); } else if (bmi < 25) { printf("You are in Normal class\n"); } else if (bmi < 30) { printf("You are in Overweight class\n"); } else if (bmi < 35) { printf("You are in Obese class 1\n"); } else if (bmi < 40) { printf("You are in Obese class 2\n"); } else { printf("You are in Obese class 3\n"); } return 0; } 

1. Function Setup & Variables

  • int main (void): The main entry point of the C program. It takes no arguments (void) and returns an integer (int).

  • float weight; and float height;: Declares two variables using the float data type to store decimal numbers for weight and height.

2. Gathering User Input

  • Weight Input:

printf("Please enter your weight in kg: "); displays a prompt on the screen.

  • scanf("%f", &weight); reads the floating-point number (%f) entered by the user and saves it to the weight variable using its memory address (&weight).

  • Height Input:

printf("Please enter your height in cm: "); asks the user for their height.

  • scanf("%f", &height); captures that height in centimeters.

3. Unit Conversion & Calculation

  • height = height / 100;: Converts the height from centimeters into meters, because the standard BMI formula requires height to be measured in meters.

  • float bmi = weight / (height * height);: Calculates the BMI using the formula $\text{weight} / \text{height}^2$.

  • printf("Your BMI is %.1f\n", bmi);: Prints out the final calculated BMI, formatting it to display only 1 decimal place (%.1f).

4. Categorization (The if-else Ladder)

The program checks your calculated bmi value against standard clinical thresholds from top to bottom, executing the first block that matches:

  • bmi < 16: Prints Severe Thinness class.

  • bmi < 17: Prints Moderate Thinness class.

  • bmi < 18.5: Prints Mild Thinness class.

  • bmi < 25: Prints Normal class.

  • bmi < 30: Prints Overweight class.

  • bmi < 35: Prints Obese class 1.

  • bmi < 40: Prints Obese class 2.

  • else: Catches everything else (40 or higher) and prints Obese class 3.

5. Program Completion

  • return 0;: Tells the operating system that the program has run and finished successfully.

Discount Calculator

 int main(void) { float price, discount, discounted_price; printf("Enter the original price: "); scanf("%f", &price); printf("Enter the discount percentage: "); scanf("%f", &discount); discounted_price = price - (price * (discount / 100)); if (discounted_price < 0) { printf("Error: Discounted price cannot be negative.\n"); } else { printf("The discounted price is: %.2f\n", discounted_price); } printf("discounted price is: %.2f\n", discounted_price); return 0; } 

1. Variable Declarations

  • float price, discount, discounted_price;: Declares three variables using the float data type to handle decimal numbers for the original item price, the discount percentage, and the final calculated price.

2. Getting User Inputs

  • Original Price: printf("Enter the original price: "); prompts the user, and scanf("%f", &price); reads the floating-point value into the price variable.

  • Discount Percentage: printf("Enter the discount percentage: "); prompts for the discount, and scanf("%f", &discount); stores it in the discount variable.

3. The Calculation

  • discounted_price = price - (price * (discount / 100));:

First, it converts the discount percentage into a decimal by dividing by $100$ (discount / 100).

  • Next, it multiplies that decimal by the original price to find the discount amount (price * ...).

  • Finally, it subtracts that amount from the original price to get the final discounted total.

4. Conditional Check (Validation)

  • if (discounted_price < 0): Checks if the resulting price is nega...