Reputation: 3129
So I'm trying to make part of a code where it writes something, then overwrites it. Like this:
10 seconds have passed
11 seconds have passed
12 seconds have passed
without using a new line to print it. So I don't want to use something like this:
std::cout<<"10 seconds have passed\n"
std::cout<<"11 seconds have passed\n"
How do I do this? I'm running Kubuntu Linux
Upvotes: 2
Views: 17288
Reputation: 1575
#include <conio.h>
#include <consoleapi.h>
void gotoxy(short x, short y)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD position = { x, y };
SetConsoleCursorPosition(hStdout, position);
}
If you need better moving in console. (i dont know why it not showing corectly #include conio.h
Upvotes: 5
Reputation: 110668
That's what the carriage return character is for: \r
. It is named after the mechanism of typewriters that returns the paper carriage to the right so that the typist can continue typing from the beginning of a line. Try this:
std::cout << "10 seconds have passed";
std::cout << "\r11";
Of course, with no delay between the two (except perhaps waiting on I/O), you're unlikely to see the change, but you will at least see the output as 11 seconds have passed
with 10
nowhere to be seen.
How to display the carriage return is entirely up to whatever you're outputting to, but this is its intention. For more complex cross-platform terminal output, take a look at ncurses.
Upvotes: 10
Reputation: 2613
The carriage return '\r'
is responsible for moving back to beginning of line.
Not that you have to override all characters that have been written because they are not deleted automatically on display.
And don't forget to call the flush of std::cout because otherwise on unix machines you may not see any results until its flushed.
Upvotes: 1
Reputation: 126827
Besides \r
(that takes you back to the beginning of the line), you can also use the \b
character to get back of one character. If you have to do more complicated stuff, you'll have to use the VT100 escape codes or some library (like ncurses).
Upvotes: 2
Reputation: 47945
Try
cout<<"\roverride"
With no linebreak at the end. The \r means carage return which means to jump to the beginning of a line.
Upvotes: 1