Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Erase line in C++ console program

  1. Nov 16, 2011 #1
    1. The problem statement, all variables and given/known data
    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.

    2. Relevant equations
    - nil -

    3. The attempt at a solution

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

    if(getch() == 0x0d)

    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?
  2. jcsd
  3. Nov 16, 2011 #2
    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;

  4. Nov 16, 2011 #3


    User Avatar
    Gold Member

    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.
  5. Nov 16, 2011 #4


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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.
  6. Nov 17, 2011 #5


    User Avatar
    Science Advisor
    Homework Helper

    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook