C++ Primer Chapter 14 readStr example won't compile in Visual Studio 2019

Viewed 82

The example code for the book C++ Primer has an example in chapter 14 named readStr.cpp which has compilation errors when I use cl. I'm on windows 10 and have installed Visual Studio 2019. I've also tried compiling using g++ and get similar compilation errors. I've also tried compiling this on my macbook pro and get a similar error. Could someone please advise me of the reason for the problem and provide code that corrects it? Other examples from the book's source code also produce the same compilation error. The error is :

readStr.cpp(32): error C2440: 'return': cannot convert from 'std::basic_istream<char,std::char_traits<char>>' to 'bool'
readStr.cpp(32): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

The code is :

#include "Version_test.h"

#include <algorithm>
using std::for_each;

#include <iostream>
using std::cin; using std::cout; using std::endl; using std::cerr;
using std::istream; using std::ostream;

#include <string>
using std::string; 

#include <vector>
using std::vector;

class PrintString {
public:
    PrintString(ostream &o = cout, char c = ' '): 
        os(o), sep(c) { }
    void operator()(const string &s) const { os << s << sep; }
private:
    ostream &os;   // stream on which to write
    char sep;      // character to print after each output
};

class ReadLine {
public:
#ifdef DELETED_FCNS
    ReadLine() = delete;
#endif 
    ReadLine(istream &i) : is(i) { }
    bool operator()(string &s) const { return getline(is, s); }
private:
    istream &is;
};

int main()
{
    vector<string> vs;
    ReadLine rl(cin);    // object that read lines from cin
    string s;
    while (rl(s))        // store what rl reads into s
        vs.push_back(s);

    cout << "read : " << vs.size() << " elements" << endl;
    PrintString printer;   // uses the defaults; prints to cout 
    printer(s);            // prints s followed by a space on cout

    PrintString errors(cerr, '\n');
    errors(s);             // prints s followed by a newline on cerr

    cerr << "for_each printing to cerr" << endl;
    for_each(vs.begin(), vs.end(), PrintString(cerr, '\n'));
}
1 Answers

As you can see from the reference, from C++11 the bool operator becomes explicit. You have two choice:

  1. Compile with the previous standard (in gcc add the flag -std=c++98)
  2. Make the operator explicit in this way:

bool operator()(string &s) const { return !getline(is, s).fail(); }

Related