By default when a c++ application where the header is included, the following 4 stream objects are instantiated, cin, cout, cerr and clog(corresponding wide character types are also instantiated).
Now by default cin is connected to the standard input device which is usually the keyboard and cout, cerr and clog are connected to the standard output device which is usually the console.
My question is how we can change the devices these predefined stream objects are connected to ?
Yes, it is possible and no it doesn’t depend on the operating system. Here’s a quick demo, redirecting
coutto write to a file:Note that as a rule, I’d recommend against this though. It’s generally much cleaner (for one example) to move the code into a function that takes a reference to an ostream as its parameter, then pass the appropriate ostream or ofstream as needed. On the other hand, if you have (for example) a big chunk of existing code that already has reads/writes from/to standard streams coded in, this can let that work without rewriting it all.