Back to C Programming
2026-07-127 min read

Example: Character Input in C

Learn Example: Character Input in C step by step with clear examples and exercises.

Title: Character Input in C - A full guide for Practical Depth

Why This Matters

In programming, input is a crucial aspect as it allows the program to interact with users and external data sources. In C programming, character input plays a significant role when working with strings or individual characters. Understanding how to take character input in C can help you solve real-world problems, debug common issues, and prepare for coding interviews.

This guide will provide an in-depth explanation of character input in C, covering topics such as prerequisites, core concepts, worked examples, common mistakes, practice questions, and frequently asked questions.

Prerequisites

Before diving into character input, it is essential to have a good understanding of the following topics:

  1. Basic C syntax and data types (int, char, float, etc.)
  2. Variables and their declaration
  3. Input/Output functions like scanf() and printf()
  4. Basic control structures (if-else, loops)
  5. Data structures such as arrays and strings
  6. Pointers and memory allocation in C

Core Concept

To take character input in C, we use the scanf() function with the format specifier %c. Here's a simple example:

#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered the character: %c\n", ch);
return 0;
}

In this example, we first include the stdio.h header to access input/output functions like printf() and scanf(). Inside the main() function, we declare a variable ch of type char to store the entered character. We then use printf() to prompt the user for input and scanf("%c", &ch) to read the character and store it in the ch variable. Finally, we print the entered character using another printf() statement.

Reading a Line of Characters

To read an entire line of characters (including spaces), use the fgets() function:

#include <stdio.h>

int main() {
char str[100];
printf("Enter a line of characters: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s\n", str);
return 0;
}

In this example, we declare an array str to store the entered line of characters. We use fgets() to read the entire line and store it in the str array. The sizeof(str) argument specifies the maximum number of characters that can be stored in the array, and stdin is the default input stream for user input.

Worked Example

Let's create a simple C program that takes two characters as input and checks if they are identical.

#include <stdio.h>

int main() {
char ch1, ch2;

printf("Enter first character: ");
scanf("%c", &ch1);

printf("Enter second character: ");
scanf("%c", &ch2);

if (ch1 == ch2) {
printf("Both characters are identical.\n");
} else if (ch1 != ch2 && (ch1 >= 'A' && ch1 <= 'Z') && (ch2 >= 'A' && ch2 <= 'Z')) {
printf("The first character is uppercase, and the second character is lowercase.\n");
} else if (ch1 != ch2 && (ch1 >= 'a' && ch1 <= 'z') && (ch2 >= 'a' && ch2 <= 'z')) {
printf("The first character is lowercase, and the second character is uppercase.\n");
} else {
printf("The entered characters are not identical or alphabetic.\n");
}

return 0;
}

In this example, we take two characters as input using scanf(), compare them using conditional statements, and print the appropriate message based on the comparison result. We also check if both characters are alphabetic to provide more informative feedback to the user.

Common Mistakes

  1. Forgetting the address-of operator (&): When using scanf(), always remember to use the address-of operator (&) before the variable you want to read data into, as shown in the example above.
// Incorrect: scanf("%c", ch);
// Correct: scanf("%c", &ch);
  1. Not handling invalid input: If a non-character value (like an integer) is entered instead of a character, the program may crash or behave unexpectedly. To handle this, you can use conditional statements to check for valid input before processing it.
  1. Forgetting newline characters: After reading user input using scanf(), the buffer may still contain the newline character left over from the previous input. This can cause issues when reading subsequent lines of input. To handle this, you can use getchar() or manually add a newline character after taking user input.
  1. Not checking for end-of-file (EOF): When reading user input, it's essential to check for EOF to handle cases where the user presses Ctrl+D or Ctrl+Z to terminate the program. To do this, you can use a loop and the feof() function.
// Incorrect: while (scanf("%c", &ch) != EOF) { ... }
// Correct: while ((ch = getchar()) != EOF && ch != '\n') { ... }
  1. Not clearing the buffer: After reading user input, it's a good practice to clear the buffer using getchar() or manually adding a newline character to avoid issues with subsequent inputs, as mentioned earlier.

Practice Questions

  1. Write a program that takes a string as input and checks if it contains any duplicate characters. If yes, print the first duplicate character found.
  2. Write a program that reverses a string entered by the user using scanf().
  3. Write a program that calculates the frequency of each character in a given string.
  4. Write a program that takes two strings as input and checks if they are anagrams (i.e., contain the same characters).
  5. Write a program that takes a line of text as input and counts the number of words in it, assuming that words are separated by spaces or punctuation marks.
  6. Write a program that takes a string as input and checks if it is a palindrome (i.e., reads the same forwards and backwards).
  7. Write a program that takes two strings as input and finds the longest common substring between them.
  8. Write a program that takes a string as input and removes all duplicate characters, maintaining the order of the remaining characters.
  9. Write a program that takes a string as input and converts it to uppercase or lowercase based on user preference.
  10. Write a program that takes two strings as input and concatenates them, also handling cases where one or both strings contain spaces.

FAQ

  1. Why do I need to use the address-of operator (&) with scanf()? The scanf() function requires the memory address of the variable you want to read data into. By using the address-of operator (&), we provide that memory address to scanf().
  1. What happens if I don't handle invalid input in my program? If you don't handle invalid input, your program may crash or behave unexpectedly when encountering non-character values like integers. To avoid this, use conditional statements to check for valid input before processing it.
  1. Why do I need to clear the buffer after reading user input using scanf()? Clearing the buffer helps handle cases where the user enters multiple lines of input or leaves a newline character in the buffer, which can cause issues with subsequent inputs. To clear the buffer, you can use getchar() or manually add a newline character after taking user input.
  1. What is EOF and how do I check for it? EOF (End-of-File) is a special value that indicates there's no more data to read from the input stream. To check for EOF, you can use the feof() function or loop until scanf() returns 0, which indicates EOF has been reached.
  1. Why do I need to include stdio.h? The stdio.h header file provides declarations for standard input/output functions like printf(), scanf(), and fgets(). Including this header file allows you to use these functions in your C programs.
  1. What is the difference between %c and %s in scanf()? The %c format specifier reads a single character, while the %s format specifier reads a string of characters until it encounters a whitespace or the end of the input. Be careful when using %s, as it can lead to buffer overflow issues if not handled properly.
  1. What is the difference between getchar() and scanf("%c")? Both getchar() and scanf("%c") read a single character from standard input. However, getchar() reads the next character from the input buffer without waiting for user input, while scanf("%c") waits for the user to enter a character before reading it.
  1. What is the difference between fgets() and scanf("%s")? Both fgets() and scanf("%s") read a line of characters from standard input, but they handle whitespace differently:
  • fgets() reads a line up to a specified maximum length (including the newline character) and stops at any whitespace or EOF.
  • scanf("%s") reads a string of characters until it encounters a whitespace or the end of the input, but it does not include the newline character in the result unless the input line contains no whitespace. This can lead to buffer overflow issues if not handled properly.