gpt4 book ai didi

c - getchar() 和缓冲区顺序

转载 作者:太空狗 更新时间:2023-10-29 15:02:09 25 4
gpt4 key购买 nike

我正在阅读的一本初学者 C 语言书籍让我对 getchar() 和缓冲区顺序(尤其是与换行相关)感到困惑。它说,

Getting rid of the Enter keypress is a problem that all beginning C programmers must face. Consider the following segment of a program:

printf("What are your two initials?\n");
firstInit = getchar();
lastInit = getchar();

You would think that if the user typed GT, the G would go in the variable firstInit and the T would go in lastInit, but that's not what happens. The first getchar() doesn't finish until the user presses Enter because the G was going to the buffer. Only when the user presses Enter does the G leave the buffer and go to the program—but then the Enter is still on the buffer! Therefore, the second getchar() sends that Enter (\n) to lastInit. The T is still left for a subsequent getchar() (if there is one).

首先,我不明白作者解释为什么\n转到 lastInit而不是 T .我猜是因为我将缓冲区可视化为“先进先出”。无论哪种方式,我都不理解作者呈现的顺序背后的逻辑——如果用户输入 G , 然后 T ,然后回车,怎么会出现G被第一个 getchar() 捕获, Enter(换行符)被第二个 getchar() 捕获, 和 T被第三个 getchar() 捕获?令人费解。

其次,我自己尝试了这个(Windows 8.1 下的 VMWare 上运行的 Ubuntu 14.04,文本编辑器 Code::Blocks,编译器 gcc),我得到了作者所说的完全符合常识的结果 doesn't 发生了!: G转到 firstInitT转到 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;
}

输出是:

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;
}

输出是:

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

最佳答案

作者描述的是用户输入“G T ”的场景。

关于c - getchar() 和缓冲区顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791938/

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