Search code examples
c++getlineistream

Why is the return value of std::getline not convertible to bool?


When I run the below example code from Accelerated C++, I get the error:

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

I read in this answer that starting from C++11, getline() returns a reference to a stream which is converted to bool when it is used in a Boolean context. However, I can't figure out why the stream in my code is not "contextually convertible" to bool. Can you explain that and point me to a correct version?

#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;
}

Solution

  • You didn't add #include <istream> to your code, so the compiler doesn't know what istream is and therefore it doesn't know it is convertable to bool.

    Add #include <istream> to fix the issue.