• Support PF! Buy your school textbooks, materials and every day products Here!

Erase line in C++ console program

  • Comp Sci
  • Thread starter Deathfish
  • Start date
  • #1
86
0

Homework Statement


How do I erase previous lines displayed from printf function? (use printf, scanf etc)

Welcome to Sample Program
[Press Enter to Start]

When I press Enter, the [Press Enter to Start] should disappear.


Homework Equations


- nil -


The Attempt at a Solution



unsigned char mainstart=0;
printf("SAMPLE PROGRAM");
printf("\n==============================");
while(mainstart!=1)
{
printf("\n[Press Enter to start]");
getch();
while(getch() != 0x0d);

if(getch() == 0x0d)
{
mainstart=1;
}
}

Also, why does my code only function when I press Enter three times? How do I alter the program to function by pressing Enter only once?
 

Answers and Replies

  • #2
437
0
Depends on the OS. Some allow escape sequences and/or provide libs that let you position the cursor exactly (like curses). On Windows, use something along these lines:

HANDLE ConHandle = GetStdHandle(STD_OUTPUT_HANDLE);

COORD Pos;
Pos.X=3;
Pos.Y=3;

SetConsoleCursorPosition(ConHandle,Pos);
 
  • #3
phinds
Science Advisor
Insights Author
Gold Member
2019 Award
15,907
5,585
I think there's also an ASCII code ("tab up" maybe?) that DOS (the "command line") will recognize as meaning "go up one line" --- then you have to write a line of blanks, NOT followed by a new-line so as to stay on the line you just erased.
 
  • #4
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
18
Also, why does my code only function when I press Enter three times? How do I alter the program to function by pressing Enter only once?
The operating system typically doesn't deliver any typed characters to your program until you hit enter. If you want to respond immediately to keypresses, you have to do something special for your operating system.
 
  • #5
AlephZero
Science Advisor
Homework Helper
6,994
291
Also, why does my code only function when I press Enter three times? How do I alter the program to function by pressing Enter only once?
You called getch() three times, and each call reads another character.

If you want to use the same character value several times, call getch() once and store the character in a variable.

But in your code, only one of the getch() calls is doing anything useful, You can delete the other two calls completely, and you don't need to store the character that you read.
 

Related Threads on Erase line in C++ console program

  • Last Post
Replies
4
Views
4K
Replies
3
Views
25K
  • Last Post
Replies
0
Views
3K
  • Last Post
Replies
10
Views
1K
  • Last Post
Replies
1
Views
303
Replies
2
Views
1K
Replies
5
Views
755
  • Last Post
Replies
1
Views
1K
Top