The input buffer is a block of memory set aside to store the keystrokes until the program is ready for them.
Consider this code:
1 2 3 4
|
char ch;
cout << "Enter a character: " << endl;
cin >> ch;
cout << "Char was:" << ch << endl;
| |
What is it that you actually enter from the keyboard?
If you just press 'enter', nothing really happens, the program just waits for more input. If you just press any character, again nothing happens. You may in fact type several characters. All of them are stored in the buffer. Then you press 'enter'.
Now the program processes the buffer. The first non-whitespace character is assigned to the variable ch. Anything else you typed, including pressing the 'enter' key, remains in the buffer. Thus there may now be several characters waiting in the input buffer. At the minimum, the newline character '\n' will be in the buffer.
At the next operation using cin, the characters from the buffer will be received first, before anything else which is typed.
What actually happens depends on the type of operation. Some operations ignore leading whitespace (such as space, tab or newline) but the getline function will accept everything up to the first newline, and the newline itself is discarded.
1 2 3 4 5 6 7 8 9 10
|
char ch;
string str;
cout << "Enter a character: " << endl;
cin >> ch;
cout << "Enter a string: " << endl;
getline(cin, str);
cout << "Char was:" << ch << endl;
cout << "\String was:" << str << endl;
| |
input: "a\n"
output:
Enter a character:
a
Enter a string:
Char was:a
String was: |
Try entering several characters. Input: "asdfg\n"
Output:
Enter a character:
asdfg
Enter a string:
Char was:a
String was:sdfg |
In the first case, the string is empty, "". In the second it is "sdfg".
But in neither case does the user get the opportunity to actually type anything. That's because of the characters, including the newline which were already in the buffer as a result of the previous operation.
The solution is to use ignore() to remove anything from the buffer before attempting the getline() operation.
I tend to use something like
cin.ignore(1000,'\n');
which will remove up to 1000 characters, or until the newline '\n' is reached and removed.
To ignore an unlimited number of characters, use
#include <limits>
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );