Home > Enterprise >  How to assign "cout" to another object of ostream class?
How to assign "cout" to another object of ostream class?

Time:09-18

My code

std::ostream a = std::cout; 

throws the following error:

"std::basic_ostream<_CharT, _Traits>
 ::basic_ostream(const std::basic_ostream<_CharT, _Traits> &) 
 [with _CharT=char, _Traits=std::char_traits<char>]" 
(declared at line 404 of "/usr/include/c  /11/ostream") is inaccessible

How does changing it to std::ostream& a = std::cout; fix it?

CodePudding user response:

You can't reassign the whole stream, but you can swap out the underlying buffer using rdbuf()

#include <sstream>
#include <iostream>

std::ostringstream alternative; // get an alternative stream
std::streambuf* original = std::cout.rdbuf();  // remember the original cout buffer
std::cout.rdbuf(alternative.rdbuf()); // replace cout buffer with string buffer

doSomething();

std::cout.rdbuf(original); // restore original buffer

Try it online [Godbolt]

CodePudding user response:

If I have a look into my crystal ball I think you might be attempting to have a reference to an ostream where it might be std::cout or where it might be an actual file ofstream object. In that case you can use a pointer as an intermediary, while the decision is being made.

int main(){
    // default is std::cout
    std::ostream* os = &std::cout;
    if(do_i_want_os_as_a_file){
         // mind the lifetime of this object if you care.
         os = new std::ofstream(FILENAME); 
    }
    std::ostream& out = *os;
    // your outputs are now
    out << "Hello there\n";
}

I think this is neater/clearer than swapping the underlying buffer.

  • Related