When you have
cin >> foo
, data is read until either there is a space or a newline (\n) character. For example, if you had:
1 2 3 4
|
std::string str("");
std::cout << "Enter a sentence: ";
std::cin >> str;
std::cout << '\n' << str << std::endl;
|
Then your output might be:
Enter a sentence: This is a sentence.
This
|
As you can see, only one word is read in while the rest is left in the buffer.
getline(cin,foo)
is different in that it also reads in spaces. It will only stop at the first newline character or whatever delimiter you decide to set.
The previous code snippet can be expanded to:
1 2 3 4 5 6 7
|
std::string str(""), str2("");
std::cout << "Enter a sentence: ";
std::cin >> str;
std::cout << '\n' << str << std::endl;
std::cout << "What was left in the buffer: ";
std::getline(cin,str2);
std::cout << str2;
|
Now your output could look like:
Enter a sentence: This is a sentence.
This
What was left in the buffer: is a sentence.
|
Another major difference between using
cin >> foo
and
getline(cin,foo)
is that the first will leave a newline in the buffer while the latter does not. Therefore, it is recommended to not have a mixture of these two calls in your code. Otherwise,
getline(cin,foo)
might read in a newline left by a
cin >> foo
call, and would end up looking as if it were "skipped over."
Additional info:
There is also another version of getline for character array parameters.
|
cin.getline(cstring_holder, number_of_char_to_read);
|