【问题标题】:Why this Github project converts a string to bool?为什么这个 Github 项目将字符串转换为布尔值?
【发布时间】:2017-10-02 04:43:52
【问题描述】:

这是 Github 上一个非常流行的生物信息学 C++ 项目:

https://github.com/jts/sga/blob/master/src/Util/ClusterReader.cpp

有一行:

bool good = getline(*m_pReader, line);

这行我编译不出来,也不知道作者为什么要这么做。

根据documentation,getline返回一个字符串而不是bool。确实,这是我在尝试编译项目时得到的:

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);

为什么 C++ 代码将字符串转换为布尔值?这怎么可能?

【问题讨论】:

  • 否,std::getline 返回原始流,如果没有错误,流上的布尔类型转换将返回 true。你用的是什么编译器?如果你想解决这个问题,你可以将这一行修改为bool good = getline(*m_pReader, line).good();
  • 这表明存在编译器错误(包括编译器和库安装之间可能不匹配);您使用的是什么编译器和设置?

标签: c++ type-conversion implicit-conversion


【解决方案1】:

std::getline 不返回 std::string,而是返回 std::basic_istream。对于getline(*m_pReader, line);,它只返回*m_pReader。

std::basic_istream 可以通过std::basic_ios::operator bool(C++11 起)隐式转换为bool,

如果流没有错误并且准备好进行 I/O 操作,则返回 true。具体来说,返回!fail()。

在C++11之前可以隐式转换为void*,也可以转换为bool。

您的编译器似乎无法执行隐式转换,您可以使用!fail() 作为解决方法,例如

bool good = !getline(*m_pReader, line).fail();

【讨论】:

    【解决方案2】:

    看到这个question。

    用户 Loki Astari 在他的回答中写道:

    getline() 实际上返回对它所使用的流的引用。 当流在布尔上下文中使用时,它被转换为 可在布尔上下文中使用的未指定类型 (C++03)。在 C++11 已更新,已转换为 bool。

    这意味着您可能不使用最新的编译器(C++03 甚至更好的 C++11)。如果您使用g++ 或gcc,请尝试在命令中添加-std=c++11。

    【讨论】:

      猜你喜欢
      • 2016-02-27
      • 2018-09-07
      • 1970-01-01
      • 2012-03-10
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多