繁体   English   中英

C- getchar()重新读取字符?

[英]C- getchar() re-read characters?

有没有办法让我可以用getchar()读取一个字符,并用另一个getchar()读取相同的字符?

例如,用户给出5,第一个getchar()读取5,然后第二个getchar()重新读取5。

提前致谢!

是的,您可以使用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'!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM