1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
#include <fstream>
#include <memory>
int main()
{
std::streambuf* stdout_buffer = std::cout.rdbuf() ; // the buffer that sends output to stdout
std::filebuf fbuf ;
fbuf.open( "/tmp/half_of_jabberwocky", std::ios::out ) ; // the buffer that sends output to a file
std::streambuf* file_buffer = std::addressof(fbuf) ;
const char* const jabberwocky[] =
{
"’Twas brillig, and the slithy toves",
"Did gyre and gimble in the wabe:",
"All mimsy were the borogoves,",
"And the mome raths outgrabe.",
"“Beware the Jabberwock, my son!",
"The jaws that bite, the claws that catch!",
"Beware the Jubjub bird, and shun",
"The frumious Bandersnatch!”",
"He took his vorpal sword in hand;",
"Long time the manxome foe he sought—",
"So rested he by the Tumtum tree",
"And stood awhile in thought."
};
for( const char* line : jabberwocky )
{
static int n = 0 ;
// std::cout forwards the characters to be written to the buffer
// the buffer periodically flushes the characters to the output device
// (in this case, at the end of each line, because std::cout asks it to flush the buffer.)
std::cout << ++n << ". " << line << '\n' ;
// switch buffers after each line.
// if the buffer is stdout_buffer, output will be written to stdout
// if it is file_buffer, output will be written to the file
std::cout.rdbuf( n%2 == 1 ? file_buffer : stdout_buffer ) ; // replace buffer
}
std::cout.rdbuf( stdout_buffer ) ; // restore original buffer
}
|