C – Read Single Character using Scanf()

To read single character entered by user via standard input in C language, use scanf() function.

scanf() reads input from stdin(standard input), according to the given format and stores the data in the given arguments.

So, to read a single character from console, give the format and argument to scanf() function as shown in the following code snippet.

char ch;
scanf("%c", ch);

Here, %c is the format to read a single character and this character is stored in variable ch.

Examples

In the following example, we read a single character input by the user in standard input to a variable ch using scanf() function.

main.c

#include <stdio.h>

int main() {
    char ch;
    printf("Enter a character : ");
    //read input from user to "ch"
    scanf("%c", &ch);
    //print to console
    printf("You entered %c\n", ch);
    return 0;
}

Output

Enter a character : A
You entered A
Program ended with exit code: 0

Even if you enter multiple characters, scanf() in the above program reads only one character, because it is formatted to read only one character.

Output

Enter a character : Nemo
You entered N
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to read a single character entered by user via standard input using scanf() function.