为什么scanf函数返回控制在pressing程序回车键? [英] Why does scanf returns control back to the program on pressing Enter key?

查看:156
本文介绍了为什么scanf函数返回控制在pressing程序回车键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的程序。

void main()
{
   int   *piarrNumber1   = (int *) calloc(1, sizeof(int));
   int   iUserInput      = 0;

   scanf("%d", &iUserInput);
   piarrNumber1[(sizeof piarrNumber1 / sizeof(int)) - 1] = iUserInput;
   printf("\n%d\n", piarrNumber1[0]);
}

我输入3,接着从键盘的TAB。什么都没发生。然后,我preSS Enter键。我得到3印刷程序结束。

I input "3" followed by a TAB from the keyboard. Nothing happens. Then, I press Enter Key. I get "3" printed and the program ends.

如果TAB[Horizanotal Tab]键和Enter[换行符]都是空白字符,为什么他们的行为有什么不同?

If "TAB" [Horizanotal Tab] and "Enter" [Newline] are both whitespace characters, why is their behaviour different?

推荐答案

大多数操作系统缓冲键盘输入,使他们能够正确处理退格 - 操作系统在缓冲区中保留输入,只有它给人以程序时<大骨节病>输入被击中。

Most OSes buffer keyboard input so that they can process backspaces properly -- the OS keeps input in a buffer and only gives it to the program when Enter is hit.

大多数操作系统还提供的方式来控制,但方式是不同的操作系统不同。在POSIX系统中, tcsetattr 命令用于控制该终端的缓冲,有很多其他的东西一起。你可以阅读的termios(3)许多关于它的信息手册页。你得到你想要设置非规范模式的行为:

Most OSes also provide ways to control this, but the way is different for different OSes. On POSIX systems, the tcsetattr command is used to control this terminal buffering, along with lots of other things. You can read the termios(3) manual page for lots of information about it. You get the behavior you want by setting non-canonical mode:

#include <termios.h>
#include <unistd.h>
    :
struct termios attr;
tcgetattr(0, &attr);
attr.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &attr);

这会导致操作系统每个按键发送到你的程序立即(除了少数特殊的人它拦截,像<大骨节病> CTRL-C ),而无需等待<大骨节病>输入且未经处理或者退格

which causes the OS to send every keystroke to your program immediately (except for a few special ones it intercepts, like ctrl-C), without waiting for Enter, and without processing backspaces either.

请注意该终端设置跨使用相同的终端程序持久的,所以你可能要到原来的设置保存为你的程序启动时,恢复他们在退出前。

Note that terminal settings are persistent across programs that use the same terminal, so you probably want to save the original settings as of when your program started and restore them before it exits.

这篇关于为什么scanf函数返回控制在pressing程序回车键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆