In C++, istream
has a method called getline
which operate on a C-style character array. I know there are other independent getline
functions which operate on an istream
and a std::string
. But why a separate method? Why not put it in istream
? And why does istream
's getline only work on C-style strings instead of std::string
?
Why does std::istream::getline not operate on std::string?
171 views Asked by asdacap At
2
There are 2 answers
0
On
I think the strings library and the streams library were developed separately. I think that is why we don't have universal std::string
support in the streams library. Although that has been addressed a little but with std::fstream::open
now taking strings.
One thing to note is that std::istream::getline
is more secure than std::getline
so should be preferred in some situations.
The problem is std::getline
has no checking on the length of string that will be read. That means malicious code (or a corrupt data source) can blow the memory by presenting data containing a very long line.
With std::istream::getline
you have a limit on how much can be read.
My thought is that it is designed for performance reason. You can allocate a block of buffer just once, and could iteratively process line-by-line. Note that
std::getline
which takesstd::string
as argument, callss.erase()
before writing tos
and it may causes
to allocate more buffer if the line is too long.