getchar() in C - Source Code Example

In this source code example, we will see how to use the getchar() function in C programming with an example.

getchar() Function Overview

The getchar() function in C is used to read a single character from the standard input (usually the keyboard) and then return it.

Source Code Example

#include <stdio.h>

int main() {
    char ch;

    printf("Please enter a character: ");

    // Reading input from user using getchar
    ch = getchar();

    // Display the read character
    printf("You entered: %c\n", ch);

    // Use of getchar() for holding the output screen
    printf("Press any key to exit...\n");
    getchar();

    return 0;
}

Output

Please enter a character: R
You entered: R
Press any key to exit...

Explanation

1. We prompt the user to enter a character using printf.

2. We use the getchar() function to read the character entered by the user.

3. The entered character is displayed using printf.

4. The last getchar() is used to hold the output screen until the user presses another key. 

This is a common technique to prevent the console from closing immediately.


Comments