Basic character input with getchar
What you'll learn: How to capture a single character from the user using the getchar() function.
The character catcher
While you may have used scanf to grab numbers or words, sometimes you need to be more precise. Imagine you are standing at a toll booth where you only accept one coin at a time. In C, getchar() is that toll booth. It waits for the user to press a key and hit "Enter," then it grabs exactly one character from the top of the pile.
The name stands for "get character." It is the simplest way to interact with the Standard Input (stdin), which is usually your keyboard.
How it works
Even though getchar() captures a character, it actually returns an integer (int). This is a bit of C "under the hood" magic. C uses the integer to represent the character's numeric code (like ASCII). This also allows the function to return a special value called EOF (End Of File) if something goes wrong or the input ends, which a standard char variable couldn't easily signal.
Here is how you use it in a program:
#include <stdio.h>
int main() {
int letter;
printf("Type a character and press Enter: ");
// getchar() waits for input and returns the first character
letter = getchar();
printf("You typed the character: %c\n", letter);
printf("Its numeric ASCII code is: %d\n", letter);
return 0;
}
The "Enter" catch
One important thing to remember is that getchar() is "line-buffered." This means the computer won't actually hand the data over to your program until the user presses the Enter key.
If a user types "Apple" and hits Enter, getchar() will grab the 'A' and leave 'p', 'p', 'l', 'e', and the 'newline' character sitting in a hidden waiting area called the input buffer. If you called getchar() a second time immediately after, it wouldn't wait for new typing; it would simply snatch the 'p' that was left behind.
Key takeaway
Use getchar() to read one character at a time from the keyboard, but remember that it returns an int and waits for the Enter key to be pressed.