fork download
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. class cerr_redirector
  5. {
  6. public:
  7. cerr_redirector(std::ostream& os)
  8. :backup_(std::cerr.rdbuf())
  9. ,sbuf_(os.rdbuf())
  10. {
  11. std::cerr.rdbuf(sbuf_);
  12. }
  13.  
  14. ~cerr_redirector()
  15. {
  16. std::cerr.rdbuf(backup_);
  17. }
  18.  
  19. private:
  20. cerr_redirector();
  21. cerr_redirector(const cerr_redirector& copy);
  22. cerr_redirector& operator =(const cerr_redirector& assign);
  23.  
  24. std::streambuf* backup_;
  25. std::streambuf* sbuf_;
  26. };
  27.  
  28.  
  29. int main()
  30. {
  31. {
  32. std::ostringstream os;
  33. cerr_redirector redirector(os);
  34. std::cerr << "This is written to the stream" << std::endl;
  35.  
  36. std::cout << "This is written to stdout" << std::endl;
  37.  
  38. std::cout << "and now: " << os.str() << std::endl;
  39. }
  40. std::cerr << "Redirector has been been destroyed. Standard error restored." << std::endl;
  41. }
  42.  
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
This is written to stdout
and now: This is written to the stream