thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

C++ How to use the same line to print text after delete previous?

I would like to print a line, than delete it, than print another one in the same line. I would like this because I do not to loose or go to much back for getting the information that was printed before the loop where I print things like Processing file <X>. I know that it is possible, because I have seen stuffs like that, but I did not found the way to do it.

This is my code:

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;

This prints me a lot of lines between the first and second important informations. I would like to print all the processing file X info to see that it is not getting stuck on some file. At the end I need the important info, so Is there a statement to do what I want?

Upvotes: 4

Views: 5308

Answers (1)

Mr. Llama
Mr. Llama

Reputation: 20919

You can use a VT100 escape code to clear the line, followed by a carriage return \r. Most terminals, including xterm and the Visual Studio Community 2019 console, are VT100 aware. To make sure to print the line, you can end with a std::flush. After the end of the for loop you can follow the latest progress line with a newline and a completion report.

The end result will look something like:

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;

See also Erase the current printed console line

Upvotes: 9

Related Questions