C++如何在删除上一行后使用同一行打印文本?

标签 c++

我想打印一行,而不是删除它,而不是在同一行打印另一行。我喜欢这样,因为我不会松动或回过头来获取在我打印 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;

另见 Erase the current printed console line

关于C++如何在删除上一行后使用同一行打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24515308/

相关文章:

c++ - 像素路径性能警告 : Pixel transfer is synchronized with 3D rendering

c++ - 识别使用的设计模式名称

c++ - MFC 图片控制

c++ - 计算能量的问题

c++ - 在 C++ 中销毁动态分配的内存(数组对象)

c++ - 使用opencv cap无法使用While循环调用函数两次

c++ - 将 minutes::rep 转换为 hours::rep

c++ - 如何使用 freetype 库使字形变粗?

c++ - float 据在 istream 输入上意外成功转换为整数

c++ - QT信号槽不工作