Welcome to our deep dive into the fascinating world of C Programming! Today, we're going to explore the getchar() and putchar() functions, essential tools for input and output in C. Let's get started! 🚀
Before we dive into getchar() and putchar(), let's talk about the fundamentals of input and output in C.
getchar() and putchar() are simple, yet powerful functions in C. They allow us to read and write individual characters, respectively.
The getchar() function reads a single character from the standard input (usually the keyboard). Let's see a simple example:
#include <stdio.h>
int main() {
int character = getchar();
printf("You entered: %c\n", character);
return 0;
}Run this program, and you'll see that it waits for you to type something and then displays what you typed.
On the flip side, the putchar() function writes a single character to the standard output (usually the console). Here's a simple example:
#include <stdio.h>
int main() {
putchar('H');
putchar('e');
putchar('l');
putchar('l');
putchar('o');
putchar('\n');
return 0;
}Running this program will print "HELLO" on the console.
Now that we understand these functions, let's see how they can be used together to create a simple, interactive program:
#include <stdio.h>
int main() {
int character;
while ((character = getchar()) != EOF) {
putchar(character);
putchar(' ');
}
return 0;
}This program reads characters from the standard input and prints them, one by one, until it reaches the end of the input (denoted by the EOF constant). Try it out and see for yourself!
What does the `getchar()` function do in C?
What does the `putchar()` function do in C?