Scott Kelly
Scott Kelly

Reputation: 23

C++ Demystified Chapter 13 (2004) Jeff Kent: Ifstream program does not return expected output

C++, expected output that is not outputting is contingent on the existence of students.dat. If students.dat does not yet exist (and it does not yet), the output would be: "(infile) = 000000000 (infile.fail()) = 1"

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

ifstream infile;
infile.open("students.dat");
cout << "(infile) = " << infile << endl;
cout << " (infile.fail()) = " << infile.fail() << endl;
return 0;

}

The error message I receive is the following:

error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char,std::char_traits<char>>' (or there is no acceptable conversion)

Thanks for the support, Scott Kelly

Upvotes: 2

Views: 64

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

That code was never really supposed to work (what does it mean to write an input stream to an output stream?!) but used to work "by accident" because streams in C++03 had an implicit conversion to void* which could be used to test the stream's status, and so you could print the value of the void*.

In C++11 the conversion has been replaced with an explicit conversion to bool, so the modern equivalent of that code (which is much clearer what it does) is:

cout << "(infile) = " << (bool)infile << endl;

or:

cout << "(infile) = " << static_cast<bool>(infile) << endl;

Upvotes: 1

Scott Kelly
Scott Kelly

Reputation: 23

I think you are right and this must be a version issue since my book is so old and I am typing in exactly what it says and it isn't working. I guess I should learn from a more updated book.

Upvotes: 0

Related Questions