Jaydeep Solanki
Jaydeep Solanki

Reputation: 2945

c++ how to create a function, that prints on terminal as well as file

I want to create a function, that prints output according to its parameter.
Like if I pass a ofstream pointer it should print the output to the respective file, whereas if i pass cout or something, that makes it print to the terminal.

Thanks :)

Upvotes: 1

Views: 369

Answers (3)

TheBuzzSaw
TheBuzzSaw

Reputation: 8826

void display(std::ostream& stream)
{
    stream << "Hello, World!";
}

...

display(cout);

std::ofstream fout("test.txt");
display(fout);

Upvotes: 3

ildjarn
ildjarn

Reputation: 62975

template<typename CharT, typename TraitsT>
void print(std::basic_ostream<CharT, TraitsT>& os)
{
    // write to os
}

This will allow to write to any stream (narrow or wide, allowing custom traits).

Upvotes: 2

mfontanini
mfontanini

Reputation: 21900

This should do it:

template<class T>
std::ostream &output_something(std::ostream &out_stream, const T &value) {
    return out_stream << value;
}

Then you would use it like this:

ofstream out_file("some_file");
output_something(out_file, "bleh");  // prints to "some_file"
output_something(std::cout, "bleh"); // prints to stdout

Upvotes: 1

Related Questions