gpt4 book ai didi

c - Kbhit 和 getchar 的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:47 24 4
gpt4 key购买 nike

考虑这个 C++ 代码块。

    if(_kbhit()){
//printf("Enter\n");
c = getchar();
int d = c;
printf("%d", d);
//printf("Exit \n");
}

我得到的输出是

sd115d100s100

如果我按 s、d,然后按 d、s。奇怪的是,当我按下某个字符时,会显示之前按下的字符的 ascii。

现在考虑,

    if(_kbhit()){
printf("Enter\n");
c = getchar();
int d = c;
printf("%d", d);
printf("Exit \n");
}

我这次得到的输出是

aEnter
97
Exit
dEnter
100
Exit
dEnter
100
Exit
aEnter
97
Exit

现在一切正常,在我按下一个字符后显示正确字符的 ascii 码。

为什么会出现这种异常?我该如何纠正这个异常?

最佳答案

如评论中所述,如果没有看到整个函数就很难确定,但我怀疑额外的 printf 语句正在为您刷新输出缓冲区,因为它们包含换行符。变化

printf("%d", d);

printf("%d\n", d);

看看是不是你想要的结果。

关于c - Kbhit 和 getchar 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44992988/

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