Why is this Github project converting a string to bool?
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 cannot compile this line, and I do not know why the author did it.
According to the documentation , it getline
returns a string, not a bool. Indeed, this is what I get when I try 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 C ++ code convert string to bool? How is this possible?
source to share
std :: getline doesn't return std::string
, but std::basic_istream
. For, getline(*m_pReader, line);
it just returns *m_pReader
.
std::basic_istream
can be implicitly 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. In particular, it returns!fail()
.
Prior to C ++ 11, it can be implicitly converted to void*
, which can also be converted to bool
.
It seems your compiler was unable to do the implicit conversion, you can use !fail()
as a workaround eg.
bool good = !getline(*m_pReader, line).fail();
source to share
See question .
User Loki Astari wrote in his answer:
getline () actually returns a reference to the stream in which it was used. When a stream is used in a boolean context, it is converted to an unspecified type (C ++ 03) that can be used in a boolean context. In C ++ 11, this has been updated and converted to bool.
This means that you are probably not using a modern compiler (C ++ 03 or even better C ++ 11). If you are using g++
or gcc
, try adding -std=c++11
to the command.
source to share