2

In C++, what happens to excess input, if it is given? Does it get stored somewhere or is completely ignored?

For example, this sample code:

#include <iostream>
using namespace std;
int main()
{
   char a, b, c;

   cout << "Enter three letters: ";

   cin.get(a).get(b).get(c);

   cout << "a: " << a << "\nb: " << b << "\nc: " << c << endl;
 return 0;
}

Which just asks for three letters, will let me type in as many as I want. Where do all the rest go? Preferably nowhere... right?

2 Answers 2

3

They go into an input buffer. When your process exits (without reading them) the buffer is discarded (and the unread contents along with it).

10
  • 1
    I don't know of anything that could give absolute confirmation of it for every possible operating system, but I don't know of (and can hardly imagine) an OS where it was otherwise either. May 30, 2012 at 6:58
  • 1
    @rofls: they (probably) don't get read if you do not read them. If however a latter part of your function tries to read from cout, then it will first have to read the garbage. May 30, 2012 at 7:00
  • 1
    @MatthieuM.: minor typo: you undoubtedly meant cin instead of cout. May 30, 2012 at 7:02
  • 1
    @rofls: you can use std::istream::ignore. Note that it stops at the delim character provided. May 30, 2012 at 7:06
  • 1
    In case you're wondering about the difference: std::istream::flush() will throw away whatever the input buffer currently holds -- no matter how little, how much, or what it is. std::istream::ignore() will remove data from the buffer up to a specified maximum, or until it reaches a specified delimiter (whichever comes first). May 30, 2012 at 7:09
2

It depends. There are several buffers in action. Typically (nothing guaranteed, but certainly the case for Unix and Windows), you'll have to press enter before your program sees any data; everything you've typed up to and including enter then goes into a buffer in your process, which is then discarded when the process terminates.

This is the default behavior, supposing that your process was started from the command line of a shell, and that standard input is connected to the keyboard. If another process has started your process, it may have reconfigured the input to behave differently; it's quite possible to configure the keyboard (at least under Unix) to send each character as it is entered, in which case, the next process to read the keyboard after you've read it will get the extra characters.

Finally, if standard input is from a file, of course, the data in the file stays where it is, as you'ld expect. If it is from a pipe, at least on Unix, the data will be discarded, and any processes still writing to the pipe will receive a signal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.