Reputation: 8126
This is a very popular C++ project for bioinformatics on Github:
https://github.com/jts/sga/blob/master/src/Util/ClusterReader.cpp
there is a line:
bool good = getline(*m_pReader, line);
I can't compile this line and I don't know why the author did that.
According to the documentation, getline
returns a string not bool. Indeed, this is what I get while I tried to compile the project:
ClusterReader.cpp: In member function ‘bool
ClusterReader::readCluster(ClusterRecord&)’:
ClusterReader.cpp:70:41: error: cannot convert ‘std::basic_istream<char>’ to ‘bool’ in initialization
bool good = getline(*m_pReader, line);
Why did the C++ code convert a string to bool? How would that be possible?
Upvotes: 3
Views: 111
Reputation: 172984
std::getline doesn't return std::string
, but std::basic_istream
. For getline(*m_pReader, line);
, it just returns *m_pReader
.
std::basic_istream
could be implicit converted to bool
via std::basic_ios::operator bool (since C++11),
Returns
true
if the stream has no errors and is ready for I/O operations. Specifically, returns!fail()
.
Before C++11 it could be implicitly converted to void*
, which could be converted to bool
too.
It seems your compiler failed to perform the implicit conversion, you can use !fail()
as a workaround, e.g.
bool good = !getline(*m_pReader, line).fail();
Upvotes: 3
Reputation: 2952
See this question.
User Loki Astari wrote in his answer:
getline() actually returns a reference to the stream it was used on. When the stream is used in a boolean context this is converted into a unspecified type (C++03) that can be used in a boolean context. In C++11 this was updated and it is converted to bool.
That means you probably do not use an up-to-date compiler (C++03 or even better C++11). If you use g++
or gcc
, try adding -std=c++11
to the command.
Upvotes: 2