c - 使用 getch() 和 getchar() 清除输入缓冲区的区别?

标签 c input buffer getchar getch

代码 1:-

char ch1, ch2;

printf("Input the first character:");

scanf("%c", &ch1); 

while(getchar()!='\n');

printf("Input the second character:");

ch2 = getchar();

在这种情况下 while(getchar()!='\n');,清除第一次输入时按下 enter-key 的效果。

代码 2:-

char ch1, ch2;

printf("Input the first character:");

scanf("%c", &ch1); 

while(getch()!='\n');

printf("Input the second character:");

ch2 = getchar();

在这种情况下 while(getch()!='\n');,不会清除第一次输入时按下 enter-key 的效果。结果证明循环是无限的。

在这种情况下,getch()getchar() 的功能有何不同?

最佳答案

来自 man getch:

Note that some keys may be the same as commonly used control keys, e.g., KEY_ENTER versus control/M, KEY_BACKSPACE versus control/H. Some curses implementations may differ according to whether they treat these control keys specially (and ignore the terminfo), or use the terminfo definitions. Ncurses uses the terminfo definition. If it says that KEY_ENTER is control/M, getch will return KEY_ENTER when you press con- trol/M.

这意味着 getch() 在读取回车键时返回 KEY_ENTER 而不是 '\n' ,因此您的 while 循环永远不会终止。

关于c - 使用 getch() 和 getchar() 清除输入缓冲区的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540869/

相关文章:

c - 这种字符串检索方法有什么缺点吗?

java - 为输入类型编号分配最大长度的最佳方法

pyqt - 如何在 PyQt Qt 环境中使用 QBuffer 和 Phonon 播放 .mp3

就地连接数组

bash - 如何按时间而不是大小对 shell 脚本输入进行分块?

c++ - llvm-ld 仍然存在于 clang 3.4 吗?

c - 我的信号处理程序中的竞争条件? (C)

更改指针的值而不在函数中调用它?

c++ - 为什么winsock没有64位API?

javascript - 按向上箭头时防止文本输入中的默认行为