25

I'm trying to find a way to pass fout or cout to a function. I realize there are logically easy ways to deal with this, like put ifs in any function that outputs data or even just write the function both ways. However, that seems primitive and inefficient. I don't believe this code would ever work, I'm putting it here to ensure it's easy to see what I'd "like" to do. Please be aware that I'm taking a algorithm design class using c++, I'm in no way a seasoned c++ programmer. My class is limited to using the headers you see.

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
void helloWorld(char);
ofstream fout;

int main()
{
    fout.open("coutfout.dat");
    helloWorld(c);
    helloWorld(f);

    return 0;
}
void helloWorld(char x)
{
    xout << "Hello World";
    return;
}
ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75

2 Answers2

46

These both inherit from ostream so try this:

void sayHello(ostream& stream)
{
    stream << "Hello World";
    return;
}

Then in main, pass in the object (cout or whatever) and it should work fine.

Kevin Anderson
  • 6,850
  • 4
  • 32
  • 54
  • It works! I knew it couldn't be as hard as I was making it. Thanks a bunch! – ChiefTwoPencils Apr 27 '12 at 19:22
  • 3
    No problem. Check out http://en.cppreference.com/w/cpp/io/basic_ostream for the base class. – Kevin Anderson Apr 27 '12 at 19:38
  • @Kevin After reading the link you gave, I think the function should return `stream` given as argument... `std::ostream& sayHello(std::ostream& stream){return stream << "Hello World";}` – GingerPlusPlus Oct 05 '14 at 11:32
  • 1
    @GingerPlusPlus - that's consistent if you want to do an override of the output operator, or allow it to be chained, but this is a simple "input-only" type of thing. There's certainly no harm from doing what you suggest, it's just not "important" either IMO. – Kevin Anderson Oct 06 '14 at 13:02
13

Yes. Let your function be

sayhello(std::ostream &os);

Then, in the function, you can use os in place of xout.

(By the way, using namespace std dumps the entire std namespace and is not recommended. A using std::cout and the like is all right, though.)

thb
  • 13,796
  • 3
  • 40
  • 68
  • Thanks. I've noticed that format seemed to be the convention. So, does a `using std::cout` create a "shortcut" making it possible to use `cout`, but leaving the rest of the std namespace in tact? – ChiefTwoPencils Apr 27 '12 at 20:13
  • @RobertoWilko: That's right. The `using std::cout` introduces the name `cout` into the current namespace for immediate use (which incidentally means that you cannot then also access a local variable named `cout`, if there were one). – thb Apr 27 '12 at 20:45
  • If you'll make a variable named cout you'll **** up the code anyway. – Íhor Mé Mar 11 '20 at 21:16