How to use the getchar function in C language?

In the C language, the function getchar() is used to retrieve a character from the input stream. Its basic syntax is as follows:

int getchar(void);

The getchar() function reads the next character from the input stream and returns it as an unsigned char converted to int. If there are no characters available to read, the function will return EOF (End of File).

Here is a simple example showing how to use the getchar() function to read characters from standard input and output them.

#include <stdio.h>

int main() {
    int c;

    printf("请输入一个字符:");
    c = getchar();

    printf("您输入的字符是:%c\n", c);

    return 0;
}

In the example above, the first step is to print a prompt message, then call the getchar() function to read the character input from the user. Finally, the read character is printed out.

It’s important to note that the getchar() function can only read one character at a time. If you need to read a string, you can use the fgets() function or repeatedly call the getchar() function in a loop.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds