Cover Image for Getchar() function in C
92 views

Getchar() function in C

The getchar() function in C is a standard library function declared in the stdio.h header file. It is used for reading a single character from the standard input (usually the keyboard) and returning its ASCII value as an integer. getchar() is commonly used to read character input from the user.

The syntax of getchar() is simple:

C
int getchar(void);

Here’s how getchar() works:

  1. When you call getchar(), it waits for the user to input a single character.
  2. Once the user enters a character and presses Enter (or Return), getchar() reads the character from the input buffer and returns its ASCII value as an int.
  3. If you want to store the character itself (not its ASCII value), you should declare a variable of type char and assign the result of getchar() to it.

Here’s a simple example of using getchar() to read a character from the user and display it:

C
#include <stdio.h>

int main() {
    char ch;

    printf("Enter a character: ");
    ch = getchar(); // Read a character

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

    return 0;
}

In this example:

  • We declare a char variable ch to store the character entered by the user.
  • We use printf to prompt the user to enter a character.
  • We use getchar() to read a character from the standard input and assign it to ch.
  • Finally, we use printf to display the character entered by the user.

Note that getchar() reads one character at a time. If you need to read a whole line of text, you may want to use functions like fgets() to read a string of characters. Also, remember that getchar() returns an integer representing the ASCII value, so you can compare it with integer values or use it in arithmetic operations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS