Getchar and Putchar in C
Getchar and Putchar
getchar()
andputchar()
are two basic input and output functions in C.These functions are used to read and write data one character at a time, or character by character.
Both
getchar()
andputchar()
are part of the stdio.h header file, which is included at the beginning of the program.
Getchar
The
getchar()
function reads a single character from the consoleThe
getchar()
function takes no arguments and returns an integer value that represents the character read from the console.If there are no more characters to be read,
getchar()
returns the special valueEOF (End Of File)
.
Putchar
The
putchar()
function writes a single character to the console.The
putchar()
function takes a single integer argument that represents the character to be written to the console.The function returns an integer value that represents the character that was written, or
EOF
if an error occurred.
The basic syntax and header files for getchar()
and putchar()
are as follows:
#include <stdio.h>
int getchar(void);
int putchar(int c);
Example
Here's an example C program that uses getchar()
and putchar()
functions to read input characters one by one and write them back to the console:
#include <stdio.h>
int main() {
char c;
printf("Enter a message: ");
while ((c = getchar()) != '\n') {
putchar(c);
}
return 0;
}
Explanation:
- We first declare a character variable
c
. - We then print a message to the console using
printf
() function, asking the user to enter a message. - We then use a
while
loop to read input characters one by one using thegetchar()
function. - The
while
loop continues until thegetchar()
function reads a newline character(\n)
, which signifies the end of the user's input. - Inside the
while
loop, each input character is immediately printed back to the console using theputchar()
function.
When this program is run, the user is prompted to enter a message. As they enter the message, each character is echoed back to the console in real-time. Once they press Enter, the program stops reading input and terminates.
Output:
Enter a message: Hello, World!
Hello, World!
The user entered the message "Hello, World!" and the program echoed the message back to the console.