【问题标题】:How do I make a stream that inserts a new line after each output operation?如何制作在每次输出操作后插入新行的流?
【发布时间】:2013-06-26 09:08:14
【问题描述】:

我想让std::cout 在每次输出操作后插入一个换行符。例如,这样做:

std::cout << 1 << 2 << 3;

std::cout << 1;
std::cout << 2;
std::cout << 3;

应该输出:

1
2
3

我该怎么做?

【问题讨论】:

    标签: c++ stream iostream


    【解决方案1】:

    一种可能性是创建您自己的简单流包装器。您需要一个模板化的 operator&lt;&lt; 将参数转发到 std::cout (或其他一些包装的流),然后添加一个 std::endl

    我不会发布整个课程,但操作员可能看起来像这样:

    template <typename T>
    my_stream_class &my_stream_class::operator<<(T const &value) {
        std::cout << value << std::endl;
        return *this;
    }
    

    【讨论】:

    • @acron 差不多,你的流操作符应该return *this;,否则你将无法做到log &lt;&lt; "Hello" &lt;&lt; "World";
    • 有什么办法可以改变它,让cout &lt;&lt; 0; cout &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3; 产生0\n123
    • @acron 是的,通过返回一个临时对象,该对象将在销毁时附加 std::endlideone.com/5ocnsj
    【解决方案2】:

    这是我尝试过的。我不知道这是否是最好的方法:

    #include <iostream>
    
    template <typename CharT, typename Traits = std::char_traits<CharT>>
    struct my_stream : std::basic_ostream<CharT, Traits>
    {
        my_stream(std::basic_ostream<CharT, Traits>& str) : os(str) {}
    
        template <typename T>
        friend std::basic_ostream<CharT, Traits>& operator <<(my_stream& base, T const& t)
        {
            return base.os << t << std::endl;
        }
    
        std::basic_ostream<CharT, Traits>& os;
    };
    
    int main()
    {
        my_stream<char> stream(std::cout);
    
        stream << 1;
        stream << 2;
        stream << 3;
    }
    

    输出:

    1
    2
    3

    不幸的是,我无法让它为单线 stream &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3 工作。

    【讨论】:

      【解决方案3】:

      不是很好,但您可以尝试使用它。基本上,我试图重载运算符'

      #include <iostream>
      using namespace std;
      
      class my_N
      {
          private:
             int number;
          public:
             //required constructor
             my_N(){
                 number = 0;
             }
             my_N(int N1){
                 number = N1;
             }
             friend ostream &operator<<( ostream &output, const my_N &N )
             {
                 output << N.number << "\n";
                 return output;
             }
      };
      
      int main()
      {
          my_N N1(1), N2(2), N3(3);
          cout << N1;
          cout << N2;
          cout << N3;
          return 1;
      }
      

      结果:

      1
      2
      3

      它甚至适用于cout &lt;&lt; N1 &lt;&lt; N2 &lt;&lt; N3;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2017-09-13
        • 2019-10-24
        • 2020-06-21
        • 2021-07-20
        • 1970-01-01
        • 2014-10-27
        相关资源
        最近更新 更多