我想打印一行,而不是删除它,而不是在同一行打印另一行。我喜欢这样,因为我不会松动或回过头来获取在我打印 Processing file <X>
之类的循环之前打印的信息。 .我知道这是可能的,因为我见过类似的东西,但我没有找到实现它的方法。
这是我的代码:
std::cout << "Print important information" << std::endl;
for (int i = 0; i < filesVec.size(); i++)
{
std::cout << "Processing file " << i << std::endl;
// processing file
}
std::cout << "Print another important information" << std::endl;
这会在第一条和第二条重要信息之间打印出很多行。我想打印所有 processing file X
信息以查看它是否没有卡在某些文件上。最后我需要重要的信息,所以有没有做我想做的事情的声明?
最佳答案
您可以使用 VT100 escape code清除该行,然后回车 \r
。大多数终端,包括 xterm 和 Visual Studio Community 2019 控制台,都支持 VT100。为确保打印该行,您可以以 std::flush
结尾。 for 循环结束后,您可以使用换行符和完成报告跟踪最新的进度线。
最终结果将类似于:
std::cout << "Print important information" << std::endl;
for (int i = 0; i < filesVec.size(); i++)
{
std::cout << "\33[2K\rProcessing file " << i << std::flush;
// processing file
}
std::cout << std::endl; // Added to not overwrite the last status message.
std::cout << "Print another important information" << std::endl;
关于C++如何在删除上一行后使用同一行打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24515308/