To read a string with spaces use std::getline
.
But!
Pay attention to what happens with >>
when it hits a delimiter. It stops and leaves the delimiter int he stream. This is not a problem so long as you only use >>
as >>
will discard all of the whitespace. std::getline
will capture that whitespace, and a common usecase is
user types in number and hits enter
user types in string and hits enter
So what happens? >>
extracts the number and stops when it hits whitespace. This leaves the end of line put in the stream by pressing enter in the stream. std::getline
comes along and the first thing it sees is... end of line. std::getline
stores an empty string and immediately returns. Now the program processes an empty string and the user, still expecting to type in a string enters a string that will be read by some future read, possibly putting the input stream into an error case and certainly giving the user a surprise.
A common solution is to use ignore(numeric_limits<streamsize>::max(), '\n');
to consume any data still in the stream up to and including the end of line before prompting the user for input and calling std::getline
.