Why do we need a buffer when we get input from the user?
For example:
chat arr[10];
cin>>arr;
// or
cin.get(arr,10);
I read that there is a temporary variable called buffer that stores the input that the user typed. So:
-
Does the compiler use the buffer just in case of char array? If the answer is “no” then when does it get used?
-
What is the reason that the compiler uses buffer in my example above?
-
If the buffer in my example above is an array, how the compiler choose its size?
There are several intermediate buffers involved, for various reasons:
The OS has an internal buffer. This depends somewhat on the input
device: the physical reads from a disk are by sector, so a buffer which
is a multiple of the sector size must be used; keyboard input is
normally buffered up until a newline character, to allow a limited
degree of editing (backspace, etc.); and so on. This is mostly
transparent to the application, although it does mean that even when
reading just a single character, the read won’t return until the user
inputs a newline.
The streambuf used by the istream has a buffer. This is done to
reduce the number of requests to the OS. The size of this buffer will
generally depend on the type of streambuf; a
filebufwill normally beoptimized for the platform file IO—big enough to effectively
reduce requests, but not so big as to induce paging. On some systems,
with some types of files, it’s possible that the
filebufreplaces itsbuffer with a memory mapping of the file.
The streambuf has functions which allow modifying its buffer management
somewhat. It’s very rare that they should be used, however; the authors
of the library have generally done a good enough job that you can’t
easily improve on it.
With regards to the
>>operator: this buffering all occurs at a lowerlevel. The
>>operator (and indeed all input from anistream)forwards requests for individual characters, or arrays of characters, to
the streambuf. This decoupling of actual input of characters from the
parsing of them is fundamental to the design of
istream:istreamtakes care of the parsing only; it contains a pointer to a streambuf
which takes care of the actual input. (Some of the parsing functions
may also contain buffers. For example,
>>of anintmay collect thesequence of digits in a buffer before starting actual conversion.)