gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:59 25 4
gpt4 key购买 nike

有没有一种方法可以让我用 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'!

关于C- getchar() 重新读取字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53750882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com