A simple C ++ loop with a pause, but the conclusion is very strange!

I'm just trying to write a program that displays a series of numbers rewriting each other on the same line of the console screen. e.g. 10 9 8 7 6 etc.

I am using xcode and compiling in xcode. And it outputs "10 121469 121468", what am I doing wrong? Why is this not so obvious?

#include <iomanip> #include <iostream> using namespace std; #ifdef __GNUC__ #include <unistd.h> #elif defined _WIN32 #include <cstdlib> #endif int main() { cout << "Description: This program will show you how much change" << endl; cout << "you will need to complete a transaction using a already" << endl; cout << "specified denomination" << endl << endl; cout << "CTRL=C to exit...\n"; for (int units = 10; units > 0; units--) { cout << units << ' '; cout.flush(); #ifdef __GNUC__ sleep(1); //one second #elif defined _WIN32 _sleep(1000); //one thousand milliseconds #endif cout << '/r'; // CR } return 0; } //main 
0
source share
3 answers

I don’t know if this answers your answer, but I saw that your CR incorrect.

 cout << '/r'; // CR 

- 2 characters (this is your 12146 printed on the screen). The correct value should be

 cout << '\r'; // CR 
+4
source

This line is incorrect:

 cout << '/r'; // CR 

These two characters you want

 cout << '\r'; // CR 
+4
source

In n * x, I use the following ANSI escape code to delete the current line and move the cursor to the beginning.

 \033[0F\033[2K 

So you would use it like this:

 cout << "\033[0F\033[2K" << units << endl; 

On the next page you can view all the details:

http://en.wikipedia.org/wiki/ANSI_escape_sequences

There is also a link on this page on how to achieve similar effects for windows.

+1
source

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


All Articles