There is a simple program that makes long calculations. I would like at each iteration of the loop to output its number (or the current percentage of completion) to the console, while preferably changing only the last line. For example, the output

Start Function result 45123 Testing ... Comleted 45% 

So, in the course of time, it would be necessary to change only the Comleted 45% line and not touch the rest. Conclusion done through cout . How to do this?

    2 answers 2

    Here is a sample code. sleep solely to create a delay.

     #include <iostream> #include <unistd.h> // для sleep int main() { for (int i = 0; i < 100; i+=10) { std::cout << "\rCompleted " << i << "% " << std::flush; sleep(1); } std::cout << "\rDone " << std::endl; return 0; } 

    std :: flush is needed, since standard threads like to buffer I / O (comment out and look at the result). \r translates the output to the beginning of a line without moving to a new line. A pair of spaces after the percentage is needed, since the string is not cleared and it is necessary to overwrite the tail with spaces.

    • Thank you for what you need. True, everything works for me without std::flush . - RussCoder
    • 2
      I think it depends a lot on the stl used (different compilers use different stl). I tested under gcc 4.8.3 on gentoo. - KoVadim
    • instead of non-standard sleep, it is better to use the standard: std::this_thread::sleep_for(std::chrono::seconds(1)); or std::this_thread::sleep_for(1s); for C ++ 14 - ixSci

    here's another way. wrote under windows but can be rewritten under linux

     #include <iostream> int main() { for (int i = 0; i < 100; i+=10) { system("cls"); // очистить терминал std::cout << "Completed " << i << "%" << std::endl; system("ping -n 2 127.0.0.1 > c:\\111.txt"); // вместо ф-ии sleep которой у меня нет } std::cout << "Done" << std::endl; return 0; } 
    • yeah, that's just cls cleans the whole screen :) - KoVadim
    • Yes, you have to recreate the elements of the output every time - perfect