1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
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==============================");
    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?
     
  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;
    Pos.X=3;
    Pos.Y=3;

    SetConsoleCursorPosition(ConHandle,Pos);
     
  4. Nov 16, 2011 #3

    phinds

    User Avatar
    Gold Member
    2016 Award

    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

    Hurkyl

    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

    AlephZero

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Erase line in C++ console program
  1. C++ console plotting (Replies: 4)

Loading...