c - C 中的 getchar() 无需按 Enter 即可完成

标签 c io getchar

来 self 的 previous post ,我开始知道 getchar() 只有在我们按下 Enter 时才会完成。让我们考虑这段代码:

#include<stdio.h>
main()
{
  getchar();
  getchar();
  getchar();
  getchar();
  getchar();


}

我预计它会像这样运行:我按一些 key1,然后按 Enter,然后按 key2 和 Enter,然后 key3 和 Enter,然后 key4 和 Enter,最后 key5+Enter,程序现在应该终止。这不是实际发生的事情。发生的事情是这样的:我按某个键 1,然后按 Enter,然后按 key2 和 Enter,然后按 key3 和 Enter,程序最终终止!

  • Why don't the last two getchar() work?

我观察到的另一件奇怪的事情是,如果我这样做:key1,key2,key3,key4+Enter 然后程序终止。例如。如果我连续按 q、w、e 和 r,然后按 Enter,程序将终止。

  • Why not all the getchar() ask for enter? Does this mean that getchar() take any other key as Enter? But then does the next key is taken as the input for the next getchar()?

让我们考虑另一个代码:

#include<stdio.h>
main()
{

  int c=getchar();
  int d=getchar();
  int e=getchar();
  printf("2 getchar are remaining\n");
  int f=getchar();
  int g=getchar();
  printf(" c is %d, d is %d, e is %d, f is %d and g is %d",c,d,e,f,g);

} 

我输入:ABCDEFG 然后回车。 2 getchar are remaining 这行应该在我按下 C 或 D 时立即打印出来。但它最后打印出来了,这意味着所有的 getchar() 都同时执行了——这很奇怪。

  • Isn't the program get executed line by line? I.e. after the third getchar, printf() should work. But it works at last when all the getchar()s are executed.

最佳答案

getchar() 在您按回车键后完成是不正确的。只要有字符要读取,getchar() 就会完成。这种差异是显着的:例如,如果您使用将标准输入重定向到文件的程序:

$ hexdump -C abcd_file 
00000000  61 62 63 64 65                                    |abcde|
00000005

$ ./in < abcd_file 
$

请注意,“abcd_file”是一个包含“abcde”的文件,没有换行符,您的程序在任何地方都不需要换行符即可完成。那是因为文件一直在提供字符而不是等待换行符。

另一方面,通用终端或终端仿真器有一种称为“规范模式”的操作模式。规范模式意味着终端支持“命令行处理工具”,并且在用户按下 ENTER 之前不会发出可用字符的信号。这就是不正确的“getchar() 等待 ENTER”故事的来源。您可以将您的终端切换出规范模式并查看它检索所有字符而无需按回车键:

$ stty -icanon; ./in; stty icanon
ggggg$

在这种情况下,没有回车的 5 个字符使程序结束。

最后,getchar() 看起来提前返回的原因是因为它还返回了 ENTER 字符。所以“a\nb\nc\n”是 6 个字符,前 5 个字符由 getchar() 返回,第六个在程序完成后从终端队列中删除。输入“abcd\n”还意味着 getchar() 将立即可用于 5 次连续读取,因为终端队列中存储了 5 个字符。

http://www.gnu.org/software/libc/manual/html_node/Noncanonical-Input.html#Noncanonical-Input

关于c - C 中的 getchar() 无需按 Enter 即可完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336297/

相关文章:

c - 为什么我不能重用 c = getchar();在 str1 上使用后在 str2 上? (C)

c - 如果有人没有写任何东西就进入然后它应该终止

c - 从 C 中的文件读取(可变长度)输入

c - 为什么我们对指针数组使用静态?

c - 字符串数组的文件输出

c++ - 代码块 : Unit test file requires entire address of a file

Java I/O 流;有什么区别?

c - 由于某种原因,向子进程发送信号丢失了。 sleep 功能的改变导致了一种奇怪的结果

c - 基于物理的小程序中的无限循环

c - 如何使用 getchar() 扫描一个单词