首页 > 解决方案 > C- getchar() re-read characters?

问题描述

is there a way that I can read a character with getchar() and read the same character with another getchar()?

for example the user gives 5 and the first getchar() reads 5 and then the second getchar() re-reads the 5.

thanks in advance!

标签: cgetchar

解决方案


是的,您可以使用ungetc()将字符放回输入流中。

这是一个示例程序:

#include <stdio.h>

int main(void) {
    printf("Type something: ");
    int c = getchar();
    printf("Ok, you typed '%c'. Putting it back...\n", c);
    ungetc(c, stdin);
    printf("Reading it again...\n");
    c = getchar();
    printf("Still '%c'. Putting it back again...\n", c);
    ungetc(c, stdin);
    printf("Reading it again...\n");
    c = getchar();
    printf("Still '%c'!\n", c);
}

运行它:

Type something: smackflaad
Ok, you typed 's'. Putting it back...
Reading it again...
Still 's'. Putting it back again...
Reading it again...
Still 's'!

推荐阅读