fork(2) download
  1. #include <iostream>
  2.  
  3. class space_delimited_output_buffer : public std::streambuf
  4. {
  5. public:
  6. space_delimited_output_buffer(std::streambuf* sbuf)
  7. : m_sbuf(sbuf)
  8. { }
  9.  
  10. virtual int_type overflow(int_type c)
  11. {
  12. return m_sbuf->sputc(c);
  13. }
  14.  
  15. virtual int sync()
  16. {
  17. if (ok_to_write)
  18. this->sputc(' ');
  19. else
  20. ok_to_write = true;
  21.  
  22. return internal_sync();
  23. }
  24. private:
  25. std::streambuf* m_sbuf;
  26. bool ok_to_write = false;
  27.  
  28. int internal_sync()
  29. {
  30. return m_sbuf->pubsync();
  31. }
  32. };
  33.  
  34. class space_delimited_output_stream
  35. : public std::ostream
  36. , private virtual space_delimited_output_buffer
  37. {
  38. public:
  39. space_delimited_output_stream(std::ostream& os)
  40. : std::ostream(this)
  41. , space_delimited_output_buffer(os.rdbuf())
  42. {
  43. this->tie(this);
  44. }
  45. };
  46.  
  47. int main() {
  48. space_delimited_output_stream os(std::cout);
  49. os << "abc" << 123 << "xyz";
  50. }
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
abc 123 xyz