Hi,
While trying a program from "C++ Primer 3rd Edition" by Stannley Lippman, I encountered with following two errors.

1. The book says that the header file fstream also includes the header iostream, so including just fstream will do. But g++ complained about cout, cin and cerr despite having fstream included and namespace std used properly. Does it mean that fstream does not include iostream, or is it specific to g++ compiler.

2. I was trying to create and initialize an ofstream object as below

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void do_something()
{
       string fname;
       cin >> fname;
       
        ofstream fout(fname);
}

g++ did not compile this and says that there is no matching call for the last statement. Isn't there a constructor in the class ofstream which accepts a string object as argument?

Does it mean that fstream does not include iostream, or is it specific to g++ compiler.

One windows header file usually includes 10/15 others, you can never be sure if it's included until you check. Besides, there's no harm in putting #include<iostream> again, that's what header guards are for.

g++ did not compile this and says that there is no matching call for the last statement. Isn't there a constructor in the class ofstream which accepts a string object as argument?

ofstream doesn't take an std::string as an argument, it has to be a const char*. Here's your fixed code:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void do_something()
{
  string fname;
  cin >> fname;

  ofstream fout(fname.c_str());
  // Do stuff with fout
}

int main()
{
  do_something();
}

Edited 7 Years Ago by William Hemsworth: n/a

This question has already been answered. Start a new discussion instead.