How to write to same line using C/C++
Posted: Sun Feb 17, 2013 12:01 am
This is an answer to AU of DigitalSriLanka Facebook group.
1. First method using \r (carriage return)
This will return to beginning of line and draw the same thing over and over
2. Second method using \b (delete one character or backspace)
Notice that I'm writing 4 characters, so I know I have to delete exactly 4 bytes to delete to redraw only the number.
First method is generally preferred. However you can select between them as appropriate.
1. First method using \r (carriage return)
This will return to beginning of line and draw the same thing over and over
Code: Select all
int i;
for (i = 0; i < 1000; i++){
//printf("%d[2K", i);
printf("\rThis is printed on the same line %d", i);
Sleep(1000);
}
Notice that I'm writing 4 characters, so I know I have to delete exactly 4 bytes to delete to redraw only the number.
Code: Select all
int i;
printf("\rThis is printed on the same line %4d", 0);
for (i = 0; i < 1000; i++){
//printf("%d[2K", i);
printf("\b\b\b\b%4d", i);
Sleep(1000);
}