为什么std::getline的返回值不能转换为bool



当我从Accelerated C++运行以下示例代码时,我得到错误:

error: value of type 'basic_istream<char, std::__1::char_traits<char> >' is not contextually convertible to 'bool'
while (std::getline(in, line)) {

我在这个答案中读到,从C++11开始,getline()返回对流的引用,当在布尔上下文中使用时,该流被转换为bool。然而,我不明白为什么我的代码中的流不是"上下文可转换";至CCD_ 3。你能解释一下并给我指一个正确的版本吗?

#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include "str_helper.h"
using std::string;
using std::vector;
using std::map;
using std::istream;
// other code here...
map<string, vector<int> >
xref(istream& in, vector<string> find_words(const string&) = split)
{
string line;
int line_number = 0;
map<string, vector<int> > ret;
// read next line
while (std::getline(in, line)) {
++line_number;
// break the input line into words
vector<string> words = find_words(line);
// remember that each word occurs on the current line
for (vector<string>::const_iterator it = words.begin(); it != words.end(); ++it)
ret[*it].push_back(line_number);
}
return ret;
}

您没有将#include <istream>添加到代码中,因此编译器不知道istream是什么,因此也不知道它可以转换为bool

添加#include <istream>以解决此问题。

您遗漏了split的定义,这使得它在添加之前不会编译。我不得不删除你对str_helper.h的私人包含

添加#include <iostream>istream似乎对我来说确实很好

您遇到的问题是,如果没有明确的include,不同的编译器和库版本会包含istreamgetline的各种部分定义。

最新更新