Hey! I've been reading through Accelerated C++, and one of the exercises in the beginning has you try out this code, and asks you to input a name with a space:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
int main()
{
std::cout << "What is your name? ";
std::string name;
std::cin >> name;
std::cout << "Hello, " << name
<< std::endl << "And what is yours? ";
std::cin >> name;
std::cout << "Hello, " << name
<< "; nice to meet you too!" << std::endl;
return 0;
}
What happens is that cin of course stops reading at the space, which is to be expected... but then it completely disregards the next cin? Why does that happen?
(e.g. instead of saying
Hello, John Doe
And what is yours?
it outputs
Hello, John
And what is yours?
Hello, Doe; nice to meet you too!
When you input something into the console, it gets put in a buffer.
The >> operator does not actually poll the user for input, it just examines the buffer. If the buffer is empty and is being polled.. then the user is prompted. But only then.
Also.. the >> operator does 2 tricky things:
1) It throws away all leading whitespace in the buffer
2) It stops once it reaches whitespace (after it finds non-whitespace)
int main()
{
// At program start... the input buffer is empty
std::cout << "What is your name? ";
std::string name;
// Here, we are using the >> operator to extract a string. So cin will
// check the input buffer. Since the buffer is empty, the user will now
// be polled for input.
//
// If you input "John Doe", then press enter... this will put "John Doe\n" in
// the input buffer (what you input, plus the newline for when you pressed enter)
//
// Since the buffer is no longer empty, the >> operator sees "John" in the buffer
// and extracts it. It does not go beyond that because it stops at whitespace
//
// Therefore, this line will put "John" in the 'name' variable
// And will leave " Doe\n" in the input buffer
std::cin >> name;
std::cout << "Hello, " << name
<< std::endl << "And what is yours? ";
// At this point, " Doe\n" is still in the input buffer. Since we are using >> again
// We check the input buffer. Since it is NOT empty, the user does not get polled.
// Instead, it just extracts what is already in the buffer.
//
// So first it throws away leading whitespace... which leaves "Doe\n" in the buffer.
// Then it extracts "Doe" leaving "\n" in the buffer
std::cin >> name;
// At this point, name=="Doe" and the input buffer is "\n"
std::cout << "Hello, " << name
<< "; nice to meet you too!" << std::endl;
return 0;
}
So yeah... short explanation is that >> stops at whitespace. If you want to take the whole line, then you can use getline instead:
std::getline( std::cin, name ); // <- will take the entire line