Assigning cout to a variable name

后端 未结 7 1546
旧时难觅i
旧时难觅i 2020-12-14 20:26

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 i

7条回答
  •  孤街浪徒
    2020-12-14 21:01

    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;
    

提交回复
热议问题