How to print on the console on a single line

Instead of it always printing on a new line, I want to overwrite the old one.
so that it doens't scroll and I can make a good console gui. that way i can output numbers in a single location.
@coercedman66

Take a look at my answer here.
http://v2.cplusplus.com/forum/general/51271/
. It shows how to specify where you want to print on screen. It may be what you needed.
If you just want to overwrite the current line, or the last few chars, you can use \r (move the cursor back to the start of the line) and \b (tab one space back). You will have to remember to overwrite chars with blanks when necessary.

It does flicker a bit if you changes too much text, but it's often used for console spinners and such like.

And while I'm not sure it's fully portable, it works on Windows and -- I believe -- most Linuses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <cstdio>
#include <ctime>
using namespace std;

const int console_height = 40;

void clear_screen()
{
	for(int m = 0; console_height > m; ++m)
	{
		printf("\n");
	}
}

void waste_time(int ticks)
{
	clock_t start = clock();
	clock_t now  = start;
	
	while(ticks > (now - start))
	{
		now = clock();
	}
}

void loading_test(int max)
{
	printf("Please wait, loading...\n");
	for(int m = 0; max >= m; ++m)
	{
		printf("\r[");
		for(int n = 0; max > n; ++n)
			printf("%c", (n < m) ? '=' : ' ');
		printf("] (%.0f%%)", (100.0 * m)/max);
		waste_time(CLOCKS_PER_SEC / 4.0);
	}

	printf("\n");
}

void stage_rocket()
{
	const char rocket[] =
	"  |\n"
	"  ^\n"
	" / \\\n"
	" | |\n"
	" | |\n"
	" | |\n"
	" | |\n"
	"/| |\\\n"
	"\n";
	
	printf(rocket);
}

void perform_count_down(int start_count)
{
	printf("Counting down: T -      "); // 6 spaces

	int count_down = start_count;
	
	const char spin[] = "\\-/|";
	int s = 0;
	
	while(0 < count_down)
	{
		printf("\b\b\b\b\b\b%-*d [%c]", 2, count_down, spin[s++ % 4]);
		for(int m = 0; 10 > m; ++m)
		{
			waste_time(CLOCKS_PER_SEC / 10.0);
			printf("\b\b%c]", spin[s++ % 4]);
		}
		--count_down;
	}
}

void launch_rocket()
{
	int ticks = CLOCKS_PER_SEC;
	
	for(int m = 0; console_height > m; ++m)
	{
		printf("\rBLAST OFF!!!");
		waste_time(ticks);
		printf("\r            \n");
		ticks = (7 * ticks) / 10;
	}
}

void count_down_test(int start_count)
{
	clear_screen();
	stage_rocket();
	perform_count_down(start_count);
	launch_rocket();
}

int main()
{
	loading_test(32);
	count_down_test(10);

	return 0;
}
Last edited on
Topic archived. No new replies allowed.