title: How to override cout in C++?
body: <p>I have a requirement, I need to use <code>printf</code> and <code>cout</code> to display the data into <code>console and file</code> as well.
  For <code>printf</code> I have done it but for <code>cout</code> I am struggling, how to do it?</p>
  
  <pre><code>   #ifdef _MSC_VER
       #define GWEN_FNULL "NUL"
       #define va_copy(d,s) ((d) = (s))
           #else
           #define GWEN_FNULL "/dev/null"
          #endif
          #include &lt;iostream&gt;
          #include &lt;fstream&gt;
  
          using namespace std;
          void printf (FILE *  outfile, const char * format, ...) 
          {
  
              va_list ap1, ap2;
              int i = 5;
              va_start(ap1, format);
              va_copy(ap2, ap1);
              vprintf(format, ap1);
              vfprintf(outfile, format, ap2);
              va_end(ap2);
              va_end(ap1);
          }
      /*    void COUT(const char* fmt, ...)
          {
              ofstream out("output-file.txt");
              std::cout &lt;&lt; "Cout to file";
              out &lt;&lt; "Cout to file";
          }*/
          int main (int argc, char *argv[]) {
  
              FILE *outfile;
              char *mode = "a+";
              char outputFilename[] = "PRINT.log";
              outfile = fopen(outputFilename, mode);
  
              char bigfoot[] = "Hello 
  
  World!\n";
          int howbad = 10;
  
          printf(outfile, "\n--------\n");
          //myout();
  
          /* then i realized that i can't send the arguments to fn:PRINTs */
          printf(outfile, "%s %i",bigfoot, howbad); /* error here! I can't send bigfoot and howbad*/
  
          system("pause");
          return 0;
      }
  </code></pre>
  
  <p>I have done it in <code>COUT</code>(caps, the commented part for the code above) . But I want to use normal <code>std::cout</code>, so how can I override it. And it should work for both <code>sting and variables</code> like</p>
  
  <pre><code>int i = 5;
  cout &lt;&lt; "Hello world" &lt;&lt; i &lt;&lt;endl;
  </code></pre>
  
  <p>Or are there anyway to capture <code>stdout</code> data, so that they can be easily written into <code>file and console</code> as well.</p>