输入缓冲在C ++中如何工作 [英] How does input buffering work in C++

查看:81
本文介绍了输入缓冲在C ++中如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个代码段.我对缓冲内部如何工作感到困惑.

Here is a code snippet. I'm confused as to how the buffering internally works.

  while(true)
  {
      cout << "Enter a character: ";
      cin.ignore(3, '\n');
      ch = cin.get();  // ch is char type
      cout << "char: ch: " << ch << endl;
  }

实际上,cin.ignore(3, '\n')会忽略前三个字符,然后获取下一个立即数.到此为止,一切都很好.因为我将其保留在while循环中,所以我试图检查ignore()get()的行为.例如,我检查的输出是

Actually cin.ignore(3, '\n') ignores the first three characters and then gets the next immediate character. Till that point its fine. Since, I kept this in a while loop, I was trying to check the behavior of ignore() and get(). For instance, the output for which I checked was

Enter a character: abcd
char: ch: d
Enter a character: efgh
char: ch: e
Enter a character: ijkl
char: ch: i
Enter a character: mnopq
char: ch: m
Enter a character: char: ch: q
Enter a character: 

只是检查缓冲,我故意给了我4个字符而不是1个字符.在第一种情况下,它很好并且得到了它.从第二开始,忽略似乎不起作用.当我输入5个字符时,我没有得到该行为.

Just to check the buffering, intentionally I was give 4 characters instead of 1. In the first case, its fine and got it. From second, the ignore doesn't seem to work. When I entered 5 characters, I din't get the behavior.

需要对此进行解释. :)

Need explanation on this. :)

推荐答案

根据std :: cin.ignore(streamsize n = 1,int delim = EOF)的文档:

According to documentation of std::cin.ignore(streamsize n = 1, int delim = EOF):

从输入序列中提取字符并将其丢弃,直到提取出n个字符或一个等于delim的比较字符为止. http://www.cplusplus.com/reference/istream/istream/ignore/

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. http://www.cplusplus.com/reference/istream/istream/ignore/

您正在将abcd\n放到stdin上.您的第一个ignore(3,'\n')会删除abc,而您的get()将获取d. \n保留在缓冲区中.

You are putting abcd\n onto stdin. Your first ignore(3,'\n') removes abc and your get() fetches d. \n remains in the buffer.

然后将efgh\n添加到现在包含\nefgh\n的缓冲区中.您的下一个ignore()读取 3个字符或换行符,无论哪个先出现.由于换行符位于缓冲区的第一位,因此只会忽略换行符.

Then you add efgh\n to the buffer which now contains \nefgh\n. Your next ignore() reads either 3 characters or a newline, whatever comes first. Since your newline is first in the buffer, only the newline is ignored.

您可能希望在请求更多输入之前清空stdin缓冲区.您可以通过修改get()调用或在请求更多输入之前添加第二个ignore()调用来实现此目的.

You probably want to empty the stdin buffer before asking for more input. You can achieve this either by modifying your get() call, or by adding a second ignore() call before asking for more input.

这篇关于输入缓冲在C ++中如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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