如何在C++中覆盖cout?

Ras*_*yak 4 c++ windows visual-studio-2010

我有一个要求,我需要使用printfcout显示数据console and file.因为printf我已经做到了,但因为cout我在挣扎,怎么办呢?

   #ifdef _MSC_VER
     #define GWEN_FNULL "NUL"
     #define va_copy(d,s) ((d) = (s))
         #else
         #define GWEN_FNULL "/dev/null"
        #endif
        #include <iostream>
        #include <fstream>

        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 << "Cout to file";
            out << "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;
    }
Run Code Online (Sandbox Code Playgroud)

我已经完成了COUT(大写,上面代码的注释部分).但是我想使用普通的std::cout,所以如何覆盖它.它应该工作两个sting and variables

int i = 5;
cout << "Hello world" << i <<endl;
Run Code Online (Sandbox Code Playgroud)

或者无论如何都要捕获stdout数据,以便它们也可以轻松写入file and console.

rig*_*old 11

如果你有另一个流缓冲区,你可以只替换std::cout's:

std::cout.rdbuf(some_other_rdbuf);
Run Code Online (Sandbox Code Playgroud)

http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf.


0x4*_*2D2 6

您可以交换底层缓冲区。这是通过 RAII 完成的。

#include <streambuf>

class buffer_restore
{
    std::ostream&   os;
    std::streambuf* buf;
public:
    buffer_restore(std::ostream& os) : os(os), buf(os.rdbuf())
    { }

    ~buffer_restore()
    {
        os.rdbuf(buf);
    }
};

int main()
{
    buffer_restore b(std::cout);
    std::ofstream file("file.txt");

    std::cout.rdbuf(file.rdbuf());
    // ...
}
Run Code Online (Sandbox Code Playgroud)


ste*_*fan 2

覆盖 的行为std::cout是一个非常糟糕的主意,因为其他开发人员将很难理解 的使用行为std::cout与平常不同。

通过简单的课程明确您的意图

#include <fstream>
#include <iostream>

class DualStream
{
   std::ofstream file_stream;
   bool valid_state;
   public:
      DualStream(const char* filename) // the ofstream needs a path
      :
         file_stream(filename),  // open the file stream
         valid_state(file_stream) // set the state of the DualStream according to the state of the ofstream
      {
      }
      explicit operator bool() const
      {
         return valid_state;
      }
      template <typename T>
      DualStream& operator<<(T&& t) // provide a generic operator<<
      {
         if ( !valid_state ) // if it previously was in a bad state, don't try anything
         {
            return *this;
         }
         if ( !(std::cout << t) ) // to console!
         {
            valid_state = false;
            return *this;
         }
         if ( !(file_stream << t) ) // to file!
         {
            valid_state = false;
            return *this;
         }
         return *this;
      }
};
// let's test it:
int main()
{
   DualStream ds("testfile");
   if ( (ds << 1 << "\n" << 2 << "\n") )
   {
      std::cerr << "all went fine\n";
   }
   else
   {
      std::cerr << "bad bad stream\n";
   }
}
Run Code Online (Sandbox Code Playgroud)

这提供了一个干净的界面,并且控制台和文件的输出相同。您可能想要添加刷新方法或以附加模式打开文件。