getchar()
Introduction
Have you ever wondered how we can read input from the keyboard in C language? Well, the answer lies in a function called getchar(). This function is a part of the standard C library and is used to read a single character from the standard input (stdin).
Working of getchar()
The getchar() function reads a character from the standard input (stdin) and returns its ASCII code. The standard input (stdin) is typically the keyboard, but it can also be redirected to a file or another input device.
#include <stdio.h>
int main()
{
int c;
c = getchar();
printf("You entered: %c\n", c);
return 0;
}
In the above example, we have used getchar() to read a character from the standard input and store it in a variable c. We have then used printf() to display the character entered by the user.
Using getchar() in a loop
The getchar() function can be used in a loop to read multiple characters from the standard input. The loop can be terminated when the user enters a specific character (such as the newline character).
#include <stdio.h>
int main()
{
int c;
printf("Enter text. Press ENTER to exit.\n");
do {
c = getchar();
putchar(c);
} while (c != '\n');
return 0;
}
In the above example, we have used getchar() in a do-while loop to read characters from the standard input until the user presses the ENTER key. We have then used putchar() to display the characters entered by the user on the screen.
Conclusion
The getchar() function is a simple yet powerful tool that allows us to read input from the keyboard or other input devices. It is a part of the standard C library and is widely used in C programming. Understanding how getchar() works is essential for any C programmer who wants to create programs that can interact with the user.
本文来源:词雅网
本文地址:https://www.ciyawang.com/gxn0a8.html
本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。
词雅网