In this article, we will write a C program to take a character input from the user.
The program asks the user to enter a character and prints it on the screen.
Sample Input:
Enter any character: A
Output:
You have entered : A
In C programming language, the most commonly used way to take input from the user is to use the scanf()
function.
The scanf()
function is a part of the standard library(stdio.h) and it is used to read formatted input from the user or an input stream. It can be used to take integers, floats, characters, doubles, etc. from the input stream.
To take a character input from the user, you can use %c as a format specifier and pass it to the scanf()
function. The value of the entered character will be stored in the variable you pass to the scanf()
.
The following C program takes a character input from the user using the scanf()
function and prints it on the output window using printf()
function:
// C program to take a character // input from the user #include<stdio.h> int main(){ // Variable to store character char ch; printf("Enter any character: "); scanf("%c", &ch); // Print character on the screen printf("You have entered : %c", ch); return 0; }
Output:
Enter any character: M You have entered : M
Method 2: Using the getchar() Function
An alternative way to take a character input from the user is to use the inbuilt getchar()
function. It is also a part of the standard library(stdio.h).
The getchar()
function reads a character entered by the user and returns it. Unlike the scanf()
function, it adds a newline character(‘\n’) at the end of the character entered by the user.
// C program to take a character // input from the user using getchar() #include<stdio.h> int main(){ // Variable to store character char ch; printf("Enter any character: "); // Take the character input from the user ch = getchar(); // Print character on the screen printf("You have entered : %c", ch); return 0; }
Output:
Enter any character: B You have entered : B
Both methods have their own advantages. The choice between them depends on your specific needs and how you want to handle user input.
That’s all for this article. Thanks for reading!