gpt4 book ai didi

c - 为什么我必须重复介绍句?

转载 作者:太空狗 更新时间:2023-10-29 15:52:57 24 4
gpt4 key购买 nike

我想读取两个字符,所以我执行以下代码:

main() {
char a,b;

printf("\nEnter the first char.. ");
a=getchar();
printf("\nEnter the second char.. ");
b=getchar();
b=getchar(); //<--I've to add this sentence because the previously doesn't work

printf("\nFirst char --> %c",a);
printf("\nSecond char --> %c",b);

}

代码不应该有效,但它确实有效。输出是正确的:

First char --> z

Second char --> z ('z' or the char there I wan to)

如果我删除第二个 getchar() 那么输出是:

First char --> z

Second char --> (Here there is no char)

如何删除第二个 getchar() 而不会出现任何错误?

因为 getchar() 之前的 fflush(stdin) 不起作用。

最佳答案

试试这个:制作一个 data 文件,两个字节 大小正好包含 ab。现在说:

./myprogram < data

瞧。

要点是,当您操作终端并按 a 后跟回车键时,您将向进程发送两个 字符,首先是 a 然后是 \n,换行符。所以第二个 getchar 获取换行符。

(并且您的终端不允许您在不按 Enter 的情况下发送单个字符,因为它有一个行缓冲区,在发送任何内容之前它会填满该行缓冲区。)

简而言之,getchar 是一个糟糕的 I/O 原语,您应该几乎总是喜欢使用 fgets 来读取整行并处理它们。

关于c - 为什么我必须重复介绍句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11820902/

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