在下一个行之前检测行尾

Detect end of line before next one

本文关键字:检测 下一个      更新时间:2023-10-16

我不知道如何在以下代码的下一条输入之前"缓冲"一行输入(并在该行上执行一些操作,例如在末尾插入换行符):

#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";

在执行下一个之前已完成。

`"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;

您可以在其析构函数中检测到它。创建一个返回临时的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