Assigning cout to a variable name

2019-01-22 20:55发布

In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like:

ofstream outFile;
if (outFileRequested) 
    outFile.open("foo.txt", ios::out);
else
    outFile = cout;  // Will not compile because outFile does not have an 
                     // assignment operator

outFile << "whatever" << endl;

I tried doing this as a Macro function as well:

#define OUTPUT outFileRequested?outFile:cout

OUTPUT << "whatever" << endl;

But that gave me a compiler error as well.

I supposed I could either use an IF-THEN block for every output, but I'd like to avoid that if I could. Any ideas?

7条回答
看我几分像从前
2楼-- · 2019-01-22 21:19

Use a reference. Note that the reference must be of type std::ostream, not std::ofstream, since std::cout is an std::ostream, so you must use the least common denominator.

std::ofstream realOutFile;

if(outFileRequested)
    realOutFile.open("foo.txt", std::ios::out);

std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);
查看更多
Animai°情兽
3楼-- · 2019-01-22 21:23

This took about two hours to get. Basically, I have a external class running a test suite. I send in a delegate to run the tests, so in order to have access to output I need to send in an output stream. I guess I could have done a different stream per test. Anyways, I wanted to pass in the ofstream to be used later.

// Main code to create Test Suite Object
ofstream debugFile("debug.txt");
TestSuiteObject* myTestSuite = new TestSuiteObject(&debugFile);

// Test Suite Object
class TestSuiteObject: public Test::Suite
{
public:
 TestSuiteObject(std::ofstream* debug) : m_debug(*debug)
 {
  m_debug << "some witty remark" << std::endl;
  TEST_ADD(TestSuiteObject::test1);
  TEST_ADD(TestSuiteObject::test2);
  TEST_ADD(TestSuiteObject::test3);

 }

 void test1();
 void test2();
 void test3();

private:
 std::ofstream& m_debug;
};
查看更多
在下西门庆
4楼-- · 2019-01-22 21:30

I think Adam's on the right track but I don't think you can assign references - you need to use a pointer instead:

std::ofstream realOutFile;
std::ostream * poutFile;

if(outFileRequested)
{
    realOutFile.open("foo.txt", std::ios::out);
    poutFile = &realOutFile;
}
else
    poutFile = &std::cout;

you could then define a reference to be the value of the pointer, but it wouldn't be global

std::ostream & outFile = *poutFile;
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-22 21:33

You can find a very detailed explanation of how to do this here: http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81?pli=1

Hopefully someone will write this up more clearly for stack overflow to take the points...

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-22 21:36

I assume your program behaves like standard unix tools, that when not given a file will write to standard output, and when given a file will write into that file. You can redirect cout to write into another stream buffer. As long as your redirection is alive, everything written to cout is transparently written to the destination you designated. Once the redirection object goes out of scope, the original stream is put and output will write to the screen again:

struct CoutRedirect { 
    std::streambuf * old; 
    CoutRedirect():old(0) {
        // empty
    }

    ~CoutRedirect() {
        if(old != 0) {
            std::cout.rdbuf(old);
        }
    }

    void redirect(std::streambuf * to) {
        old = std::cout.rdbuf(to);
    }
}

int main() {
    std::filebuf file;
    CoutRedirect pipe;
    if(outFileRequested) {
        file.open("foo.txt", std::ios_base::out);
        pipe.redirect(&file);
    }
}

Now, cout is redirected to the file as long as the pipe is alive in main. You can make it more "production ready" by making it non-copyable, because it's not ready to be copied: If the copy goes out of scope, it would restore the original stream already.

查看更多
叼着烟拽天下
7楼-- · 2019-01-22 21:38

Following Adam Rosenfield's tracks, but fixing the reference initialization problem with ternary and comma operators:

bool outFileRequested = false;

std::ofstream realOutFile;
std::ostream & outFile = outFileRequested
    ? realOutFile.open("foo.txt", std::ios::out), realOutFile
    : std::cout;

outFile << "some witty remark";

(Tested in VS)

查看更多
登录 后发表回答