提问者:小点点

将cout输出延迟到下一个输出之前


我有一些C++控制台程序,它们会在输出的最后一行显示进度信息,时间间隔固定。

在写入下一个实际输出(或更新的进度信息)之前清除此进度行;这可能来自源代码中的许多不同地方,我目前正在清除每个地方的进度线,例如:

cout << clearline << "Some real output" << endl;
...
cout << clearline << "Some other real output" << endl;
...
cout << clearline << setw(4) << ++icount << ") " << ... << endl;
...
cout << clearline << "Progress info number " << ++iprog;

这里,'clearline'是一些(依赖于系统的)字符串,比如“r332k”,它清除当前的最后一行。

我更喜欢一些更干净的东西,把源代码的变化本地化到要清除的实际行,就像:

cout << "Progress info number " << ++iprog << defer_clearline;

其中,'defer_clearline'导致'clearline'的写入被延迟到下一个cout输出之前,无论该输出发生在何处。这样我就不需要在所有其他行上使用'clearline'了。

我认为,如果'defer_clearline'是一个操纵器,并且/或者使用xalloc()和iword(),就可能做到这一点。但我没能找到任何有用的东西。这类事情有可能做吗?如果有,怎么做?


共1个答案

匿名用户

您可以非常容易地设置包装器:

// Declare the empty struct clear_line and instantiate the object cls
struct clear_line { } cls;

class out {
private:
    std::ostream &strm = std::cout;
    bool is_next_clear = false;
public:
    template <typename T>
    out& operator<<(const T& obj) {
        if(is_next_clear) {
            strm << std::endl << std::endl << std::endl; // clear logic
            is_next_clear = false;
        }
        
        strm << obj;
        return *this;
    }
    
    out& operator<<(const clear_line& _) {
        is_next_clear = true;
        return *this;
    }
};

这非常简单地存储了一个bool,用于判断是否应该清除下一个常规输出。然后,在一般情况下(模板化的标志。那就照常输出就行了。

然后,对于对象,将重载。因此,如果发送了其中一个,我们知道要翻转标志,但实际上不输出任何内容。

下面是一个使用示例:

int main() {
    out o;
    o << "Some real output" << cls;
    o << "Some other real output";
    
    return 0;
}

在这里,它正在行动:https://ideone.com/0dzwlv