【问题标题】:When using getchar(), why do you need to clear the buffer for the enter key press in the first place?使用 getchar() 时,为什么首先需要清除输入按键的缓冲区?
【发布时间】:2014-06-01 18:42:13
【问题描述】:

我是编程和学习 C 的新手:

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

=========================================

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

我知道,在第一段代码中,如果我输入ZK作为首字母,Z会放在firstInit中,而回车键代表的'\n\会放在lastInit中。剩余的 K 将存储在后续的 getchar() 中。但是,在第二段代码中,我正在阅读的书说,如果我输入 ZK 作为首字母,firstInit 将保存 Z,lastInit 将保存 K。我只是认为需要清除缓冲区每次按回车键后。

对不起,如果这个帖子不允许,如果需要,将删除。

【问题讨论】:

  • 原因很可能是由于在调用 getchar() 之前使用了“scanf()”系列函数之一。但是,这不能从提供的代码的 sn-p 中确定。请编辑问题并添加足以让其他人重现该问题的代码。

标签: c buffer getchar


【解决方案1】:

这里有两个缓冲区在起作用:一个是键盘缓冲区,另一个是 C 标准缓冲区(输入缓冲区)。
当您按下键盘按钮时,字符将存储在键盘缓冲区中。因此,当您键入 ZK together 时,它会简单地存储在键盘缓冲区中。按下 Enter 键后,它将进入 C 标准缓冲区,并带有一个字符 \n(在按下 Enter 键时生成)。
getchar 读取输入字符按性格。在第一个代码中,第一个getcharZ 读入firstInit,第二个getcharK 读入lastInit。现在,输入缓冲区中只剩下\n
除了\n 被第三个getchar 读取并被丢弃之外,第二个代码也是如此。

如果在每个字符ZK 之后按Enter 键,则必须在读取第一个字符后清除输入缓冲区才能将K 存储在lastInit 中。

【讨论】:

  • 谢谢,我想我正在阅读的书有一个关于 getchar() 的错误,说代码的第一部分存储 '\n' 到 lastInit。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多