我有一些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(),就可能做到这一点。但我没能找到任何有用的东西。这类事情有可能做吗?如果有,怎么做?
您可以非常容易地设置
// 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;
}
};
这非常简单地存储了一个
然后,对于
下面是一个使用示例:
int main() {
out o;
o << "Some real output" << cls;
o << "Some other real output";
return 0;
}
在这里,它正在行动:https://ideone.com/0dzwlv