The buffer is a block of memory where the input from the keyboard (or other stream, such as a file) is temporarily stored.
Lets say you want to input an integer.
cin >> number;
The user enters a number, and presses [enter]. The buffer looks like this:
"34\n"
When the
cin
statement reads the contents of the buffer, it stops at the last numeric character. Thus, the buffer afterwards looks like this:
"\n"
.
If the program now has a getline statement,
getline (cin, mystr);
it will read the contents of the buffer, up to and including the '\n' character. The string mystr contains
""
(an empty string) and the newline is discarded. Processing continues at the next statement.
Lets try that same process again, with different input.
The user enters a number, and may deliberately or accidentally type some other characters, and presses [enter].
cin >> number;
The user enters
" 34 asdfg \n"
.
The cin statement ignores the leading whitespace, accepts the numeric values as the integer, and leaves the remaining characters in the buffer.
Afterwards, the buffer looks like this:
" asdfg \n"
.
Now, the getline statement will again take everything up to the newline.
The string mystr contains
" asdfg "
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
using namespace std;
int main ()
{
// Try entering aomething like " 34 asdfg "
// when the integer is requested
int number;
string mystr;
cout <<"Please enter an integer value." <<endl;
cin >> number;
cout << "The number was: "<< number << "." <<endl;
cout << "Please enter a name." << endl;
//cin.ignore(1000,'\n'); // try the program both with and without this line
getline (cin, mystr);
cout << "The name was: \"" << mystr << '\"' << endl;
system("PAUSE");
return 0;
}
|
The main point is that getting an integer or other variable using
cin >> variable;
reads just enough from the input buffer to satisfy the request. Anything else will remain in the buffer, including the newline character.
The
getline()
command is in some ways more straightforward, it reads everything up to and including the newline. The newline itself is not stored, but it is removed from the buffer.
Try the above program with line 17 re-instated (currently commented out).