C ++ how to rewrite a character in the console, return the carriage to the beginning of the line does not seem to work

My question is: how to get the numbers 10 - 0 for printing on one line, rewriting each other using the WIN32 or GNUC compiler in a simple way, like my code below:

This is what I have so far:

#include <iomanip> #include <iostream> using namespace std; #ifdef __GNUC__ #include <unistd.h> #elif defined _WIN32 #include <cstdlib> #endif int main() { cout << "CTRL=C to exit...\n"; for (int units = 10; units > 0; units--) { cout << units << '\r'; cout.flush(); #ifdef __GNUC__ sleep(1); //one second #elif defined _WIN32 _sleep(1000); //one thousand milliseconds #endif //cout << "\r";// CR } return 0; } //main 

But this only prints:

10 9 8 7 6 5 4 3 2 1

+4
source share
3 answers

I made a really trivial modification (basically, just clear it and make it more readable):

 #include <iomanip> #include <iostream> using namespace std; #ifdef __GNUC__ #include <unistd.h> #define pause(n) sleep(n) #elif defined _WIN32 #include <cstdlib> #define pause(n) _sleep((n)*1000) #endif int main() { cout << "CTRL=C to exit...\n"; for (int units = 10; units > -1; units--) { cout << setw(2) << setprecision(2) << units << '\r'; cout.flush(); pause(1); } return 0; } 

This worked great with both VC ++ and Cygwin. If it does not work under control, it sounds to me like an implementation problem.

+4
source

I recommend you use ncurses or another library for this, there is no standardized way to do this.

+2
source

Have you tried the backspace character '\b' ?

0
source

Source: https://habr.com/ru/post/1345472/


All Articles