我正在阅读的初学者的C书让我对getchar()和缓冲顺序感到困惑(特别是因为它与换行有关).它说,
摆脱Enter按键是所有C程序员必须面对的问题.考虑以下计划部分:
printf("What are your two initials?\n");
firstInit = getchar();
lastInit = getchar();
Run Code Online (Sandbox Code Playgroud)
你会认为,如果用户输入
GT,那么G它将进入变量firstInit并且T会进入lastInit,但这不会发生.第一个getchar()没有完成,直到用户按Enter键,因为它G是进入缓冲区.只有当用户按下回车键并在G离开该缓冲区,并转到程序,但随后的输入是仍然在缓冲区!因此,第二个getchar()发送Enter(\n)到lastInit.在T仍然留给后续的getchar()(如果有的话).
首先,我不明白作者的解释为什么\n要去lastInit而不是T.我猜是因为我将缓冲区可视化为"先出先出".无论哪种方式,我都不理解作者所呈现的顺序背后的逻辑 - 如果用户输入G,那么T,然后输入,如何被G第一个捕获getchar(),输入(换行)被第二个捕获getchar(),并且在T由第三捕捉getchar()?令人费解.
其次,我自己尝试了这个(Ubuntu 14.04在Windows 8.1下的VMWare上运行,文本编辑器Code :: Blocks,编译器gcc),我得到了作者所说的没有发生的确切常识结果!:G去了firstInit和该T去lastInit.这是我的代码:
#include <stdio.h>
main()
{
char firstInit;
char lastInit;
printf("What are your two initials?\n");
firstInit = getchar();
lastInit = getchar();
printf("Your first initial is '%c' and ", firstInit);
printf("your last initial is '%c'.", lastInit);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
What are your two initials?
GT
Your first initial is 'G' and your last initial is 'T'.
我还创建了一个后续程序,它似乎确认换行符最后来自缓冲区:
main()
{
char firstInit;
char lastInit;
int newline;
printf("What are your two initials?\n");
firstInit = getchar();
lastInit = getchar();
newline = getchar();
printf("Your first initial is '%c' and ", firstInit);
printf("your last initial is '%c'.", lastInit);
printf("\nNewline, ASCII %d, comes next.", newline);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
What are your two initials?
GT
Your first initial is 'G' and your last initial is 'T'.
Newline, ASCII 10, comes next.
我在这里错过了什么或作者是错的吗?(或者这是编译器依赖的 - 即使作者没有这样说)?
书:C编程绝对新手指南,第3版,Greg Perry,©2014,Ubuntu 14.04,gcc编译器版本4.8.4