This code redirect the standard output to cout.txt file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
{
ofstream of("cout.txt");
of.copyfmt( cout );
cout.rdbuf( of.rdbuf() );
int i;
while ( cin >> i )
cout << i;
} // here the local of destroyes the streambuf of cout
cout << 1;
return 0;
}
Be care, because when of goes out of life, destroyes the streambuffer. Therefore the following is the correct:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
{
ofstream of("cout.txt");
of.copyfmt( cout );
streambuf *saved_buffer = cout.rdbuf();
cout.rdbuf( of.rdbuf() );
int i;
while ( cin >> i )
cout << i;
cout.rdbuf(saved_buffer);
} // here the local of destroyes the streambuf of cout
cout << 1;
return 0;
}