The standard library overload† of the input operator >>
taking an std::istream
and a std::string
as parameters, is designed to read characters from the stream into the std::string
object until a delimiter i found, and then return the altered stream (for further reads).
All whitespace characters are by default recognized as delimiters, e.g. in most implementations,
, \t
, and \n
(the true meaning of whitespace is defined by the locale's ctype
facet).
The purpose of this design is for the usage of the input operator as a tokenizer of input data, e.g.:
std::istringstream input_stream{"apple banana pear"};
std::string token;
while (input_stream >> token) {
// Token per iteration is: "apple", "banana", and "pear".
}
Here input_stream >> token
is equivalent to the call std::operator>>(input_stream, token)
which will read characters up until a delimiter into token
, and then return the stream object input_stream
. The returned stream object is finally checked as a bool
in the while
clause, which basically returns !input_stream.fail()
(see std::basic_ios::operator bool
).
If what you need is to read characters until a linebreak or end-of-file is detected then use std::getline
.
If you want to read N characters from the stream then use, e.g., std::basic_istream::read
.
Reference:
†http://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt