Introduction
Hey Ninjas! This blog will dive into the getchar() function, a useful function for reading single characters from a user input or a file. The getchar() function is part of the C standard library and is defined in the <cstdio> header. It reads a single character from the standard input (usually the keyboard) and returns it as an int value.

This blog will explore its syntax, usage, and some examples to help you understand how to use it in your programs. So, let's get started!
Also see, Literals in C, Fibonacci Series in C++
Getchar in C++
The getchar() C++ function is a function from the C standard library used to read a single character from the standard input, typically the keyboard. It is defined in the <cstdio> header and is used in the following way:
int c = getchar();
The getchar() function reads a single character from the standard input and returns it as an int value. If the end of the input is reached, it returns EOF (end of file).
Here's an example of how you can use the getchar() function to read characters from the keyboard and print them out:
#include
using namespace std;
int main() {
char c;
cout << "Enter a character: ";
c = getchar();
cout << "You entered: " << c << endl;
return 0;
}
Output:
This C++ program, when run, will output the following:
Enter a character:
This is the text prompt asking the user to enter a character. After the user inputs a character, for example, 'a', the program will output the following:
You entered: a
It will display the entered character as an output on the screen. The "return 0" in the last line signifies the end of the program, and 0 is returned to the operating system to indicate that the program terminated successfully.
In this example, the getchar C++ function reads a single character from the standard input (the keyboard) and stores it in the variable c. The character is then printed out on the screen.
It is important to note that the this function reads only one character at a time, so if you want to read a string or a line, you would need to use a loop to read characters one by one and then append them to a string.
In short, getchar C++ function is used to read a single character from the standard input and return it as an int value. It is defined in the header and helpful for reading user input, a file, or a stream.




