C ++如何在删除先前的内容后使用同一行打印文本?

the*_*oon 2 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;
Run Code Online (Sandbox Code Playgroud)

这使我在第一重要信息和第二重要信息之间打印了许多分界线。我想打印所有processing file X信息以查看它不会卡在某些文件上。最后,我需要重要信息,所以是否有声明可以做我想做的事情?

Mr.*_*ama 6

您可以使用VT100转义码来清除该行,然后使用回车键\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;
Run Code Online (Sandbox Code Playgroud)

另请参见擦除当前的打印控制台行