Use cout as ofstream object

J

Joe Hesse

Hi,

I have a C++ function that writes to an ofstream object.
I would like to sometimes use it to write to cout.
I realize that cout is of type ostream which is not ofstream.
Since cout is "kind of" an output file, there should be someway to do it.
The following code shows what I am trying to do.
------------------------------------------------
#include <iostream>
#include <fstream>
using namespace std;

void foo(ofstream & out)
{
out << "Testing";
}

int main()
{
ofstream file("test.txt");
foo(file); // works
file.close();

foo(cout); // DOESN'T WORK

return 0;
}
 
B

Barry

Joe said:
Hi,

I have a C++ function that writes to an ofstream object.
I would like to sometimes use it to write to cout.
I realize that cout is of type ostream which is not ofstream.
http://www.cplusplus.com/reference/iostream/

Since cout is "kind of" an output file, there should be someway to do it.
The following code shows what I am trying to do.
------------------------------------------------
#include <iostream>
#include <fstream>
using namespace std;

void foo(ofstream & out)

ostream& out
 
V

Victor Bazarov

Joe said:
I have a C++ function that writes to an ofstream object.
I would like to sometimes use it to write to cout.
I realize that cout is of type ostream which is not ofstream.
Since cout is "kind of" an output file,

It isn't. It's an output _stream_, not file.
there should be someway to do
it. The following code shows what I am trying to do.

Rewrite your "C++ function" to take an 'ostream' instead.

V
 
S

Salt_Peter

Hi,

I have a C++ function that writes to an ofstream object.
I would like to sometimes use it to write to cout.
I realize that cout is of type ostream which is not ofstream.
Since cout is "kind of" an output file, there should be someway to do it.

There is, the base class involved is std::eek:stream, isn't it? Why write
an interface that is locked to std::eek:fstream when the same code can be
reused to accept any derivative of std::eek:stream, including
std::eek:stringstream, std::eek:fstream and std::cout ?
The following code shows what I am trying to do.
------------------------------------------------
#include <iostream>
#include <fstream>
using namespace std;

void foo(ofstream & out)
{
out << "Testing";

}

void foo(std::eek:stream& os)
{
os << "Testing";
}
int main()
{
ofstream file("test.txt");

if(!file)
{
std::cout << "failed to open file\n";
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top