c trick ungetc function fallback character

foreword

The ungetc function is a function in the C language standard library that is used to push a character back to the input stream (usually a file stream or standard input stream) to be read later. Its function is to insert a character at the beginning of the input stream, so that the next time the character is read, the pushed back character will be read first, and then the subsequent characters will be read.

The ungetc function is usually used to handle specific situations, such as finding characters that do not meet expectations after reading characters, and need to put them back on the input stream to be reprocessed later. Its function prototype is as follows:

int ungetc(int c, FILE *stream);

in:

c is the character to push back, usually passed as an integer, which can be converted to an integer using an (int) cast.
stream is the input stream to push back characters from, usually an open file stream, or the standard input stream (stdin), etc.
The return value of the ungetc function is an integer representation of the pushed back character, or EOF (usually -1) on error.

Here is a simple example showing how to use the ungetc function to push characters back into the input stream:

#include <stdio.h>

int main() {
    int ch;

    // 从标准输入流读取字符
    printf("Enter a character: ");
    ch = getchar();

    // 检查字符是否是小写字母
    if (ch >= 'a' && ch <= 'z') {
        // 如果是小写字母,则将字符推回到输入流
        ungetc(ch, stdin);
        printf("You entered a lowercase letter: %c\n", ch);
    } else {
        printf("You did not enter a lowercase letter.\n");
    }

    return 0;
}

In this example, if the user enters a lowercase letter, the program pushes it back into the input stream, then reads that character again and outputs the appropriate message. This way, the ungetc function allows you to re-read characters without moving the file pointer.

Guess you like

Origin blog.csdn.net/wniuniu_/article/details/132698455