在下一个之前检测行尾

时间:2015-04-15 20:56:32

标签: c++ stream

我不知道如何"缓冲"一行输入(并在该行上执行一些操作,例如在末尾插入一个换行符),然后在下面的代码中输入下一行:

#include <iostream>

class Test {
  public:
    template<class T>
    Test& operator<< (T&& anything) {
        std::cout << anything;
        return *this;
    }

};

int main() {
    Test myobj;

    myobj << "hello" << "this is cool";
    // How to insert a newline here?        
    myobj << "but" << "this is NOT cool";
}

我希望能够检测到行

myobj << "hello" << "this is cool";

在下一个执行之前完成。

2 个答案:

答案 0 :(得分:1)

`"\n"` 

为你做,如下所示:

int main() {
    Test myobj;

    myobj<< "hello" << "this is cool<<"\n"";
    // How to insert a newline here?        
   myobj << "but" << "this is NOT cool";
}

或者您使用std::endl如下

myobj << "hello" << "this is cool<<std::endl;

答案 1 :(得分:0)

您可以在析构函数中检测它。创建一个返回临时函数的log()辅助函数。在完整表达式结束时,它的析构函数将运行:

class Test {
public:
    template<class T>
    Test& operator<< (T&& anything) {...}

    ~Test() { std::cout << std::endl; }
};

Test log() { return Test(); }
// ...
log() << "hello" << "this is cool";   // destructor inserts a newline here
log() << "but" << "this is NOT cool"; // here too