What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?

后端 未结 7 1536
小蘑菇
小蘑菇 2020-12-07 08:32

I tried researching the difference between cout, cerr and clog on the internet but couldn\'t find a perfect answer. I still am not cle

7条回答
  •  天命终不由人
    2020-12-07 08:52

    The difference of these 3 streams is buffering.

    1. With cerr, the output flushs
      • immediately (because cerr does not use buffer).
    2. With clog, the output flushs
      • after you finish your current function.
      • explicitly call the function flush.
    3. With cout, the output flushs
      • after you have call to any output streams (cout, cerr, clog).
      • after you finish your current function.
      • explicitly call the function flush.

    Please check the following code, and run DEBUG through 3 lines: f(std::clog), f(std::cerr), f(std::out), then open 3 output files to see what happened. You can swap these 3 lines to see what will happen.

    #include 
    #include 
    #include 
    
    void f(std::ostream &os)
    {
        std::cin.clear(); // clear EOF flags
        std::cin.seekg(0, std::cin.beg); // seek to begin
    
        std::string line;
        while(std::getline(std::cin, line))   //input from the file in.txt
            os << line << "\n";   //output to the file out.txt
    }
    
    void test()
    {
        std::ifstream in("in.txt");
        std::ofstream out("out.txt"), err("err.txt"), log("log.txt");
        std::streambuf *cinbuf = std::cin.rdbuf(), *coutbuf = std::cout.rdbuf(), *cerrbuf = std::cerr.rdbuf(),
                        *clogbuf = std::clog.rdbuf();
    
        std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
        std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
        std::cerr.rdbuf(err.rdbuf());
        std::clog.rdbuf(log.rdbuf());
    
    
        f(std::clog);
        f(std::cerr);
        f(std::cout);
    
        std::cin.rdbuf(cinbuf);
        std::cout.rdbuf(coutbuf);
        std::cerr.rdbuf(cerrbuf);
        std::clog.rdbuf(clogbuf);
    }
    
    int main()
    {
        test();
        std::cout << "123";
    }
    

提交回复
热议问题