How to write to same line using C/C++

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to write to same line using C/C++

Post by Neo » 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

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);
	}
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.

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);
	}
First method is generally preferred. However you can select between them as appropriate.
SukhdeepMankoo
Lieutenant
Lieutenant
Posts: 92
Joined: Tue Oct 27, 2009 7:50 pm

Re: How to write to same line using C/C++

Post by SukhdeepMankoo » Fri Apr 19, 2013 10:00 am

You can try this too.
Printf("%d[2K",27); // delete entire line
printf("\r%d",I); // move cursor to start of line

[ Post made via Mobile Device ] Image
SukhdeepMankoo
Lieutenant
Lieutenant
Posts: 92
Joined: Tue Oct 27, 2009 7:50 pm

Re: How to write to same line using C/C++

Post by SukhdeepMankoo » Fri Apr 19, 2013 10:01 am

For more information, see VT 100 codes

[ Post made via Mobile Device ] Image
Post Reply

Return to “C/C++ Programming”