How to use ANSI to return to a previous position out of the current window? (C++)

  ansi-escape, c++, unix, windows

I have found some functions that use ANSI escape codes to handle the Command Line. The purpose is to print a lot of contents. Then I want to return where I started. However, the implementation below just jumps to the beginning of the window. I don’t mind a Unix solution. I would prefer though a cross – platform solution.

My implementation:


#include "stdio.h"
#include "windows.h"

/**
 * Moves CLI cursor Up.
 * 
 * @param[in] positions number of rows to move cursor up
 */
void moveUp(int positions) 
{
    printf("x1b[%dA", positions);
}

/**
 * Moves CLI cursor Down.
 * 
 * @param[in] positions number of rows to move cursor down
 */
void moveDown(int positions) 
{
    printf("x1b[%dB", positions);
}

/**
 * Scrolls CLI window Up.
 * 
 * @param[in] positions number of rows to scroll up
 */
void scrollUp(int positions)
{
    printf("x1b[%dS", positions);
}

/**
 * Scrolls CLI window Down.
 * 
 * @param[in] positions number of rows to scroll down
 */
void scrollDown(int positions)
{
    printf("x1b[%dT", positions);
}

/**
 * Places CLI cursor at defined position in the CLI.
 * 
 * @param[in] x the row to place the cursor
 * @param[in] y the column to place the cursor
 */
void gotoxy(int x, int y)
{
    printf("x1b[%d;%df", x, y);
}

int main (void)
{
    for (int i = 1; i < 100; i += 1)
    {
        gotoxy(i,0);
        printf("%dn", i);
    }
    gotoxy(0,0);
    printf("Hello Worldn");
}

Any help is appreciated!

Source: Windows Questions

LEAVE A COMMENT