How does input buffering work in C++

岁酱吖の 提交于 2019-12-25 05:30:54

问题


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

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: 

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. :)


回答1:


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

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/

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

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.

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.




回答2:


cin.ignore(3, '\n') ignores up to three characters, stopping after it finds the end of a line (i.e. a \n character).

After the first line of input, the buffer will contain 5 characters, abcd\n. So ignore ignores abc, and get gets d, leaving \n.

After the second line, it contains \nefgh\n. So ignore just ignores the end-of-line character, and get returns e.

If you want to discard the rest of line after extracting the character, then use ignore again:

cin.ignore(numeric_limits<streamsize>::max(), '\n');


来源:https://stackoverflow.com/questions/16732793/how-does-input-buffering-work-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!