-1

I have been dealing with a issue that I cant solve in specifically c language in output terminal I want my cursor in previous line for example

prints("hello\n");
prints("Hi");

If want to print hi in near horizontal to hello but not my removing \n or by re writing anything I just want that after \n cursor go to previous line and print hi can anyone help me please

prints("\n hi\r\b");
prints("hello");

I wanted it to be like hello hi

Mathieu
  • 8,840
  • 7
  • 32
  • 45
  • 3
    C standard does not supoort this. Depending on terminal, you can try so called ANSI codes, or VT100. – hyde Nov 29 '22 at 11:58
  • For Windows console, Win32API has a bunch of console related calls. For Linux/Unix, ncurses is the de facto standard library for terminal control. – hyde Nov 29 '22 at 12:12
  • ISO C does not provide any means of moving the cursor around the screen at will, except for the backspace character. However, most [platforms](https://en.wikipedia.org/wiki/Computing_platform) provide different kinds of extensions which do offer such functionality. Therefore, if you want your question to be answerable, you will have to specify which platform (e.g. operating system) you are asking about. – Andreas Wenzel Nov 29 '22 at 12:16
  • It's not portable or universal, and it's not necessarily the best way to do it, but to get started, you can probably move the cursor up, down, left, and right by using `printf("\033[A")`, `printf("\033[B")`, `printf("\033[C")`, and `printf("\033[D")`. (I forget which is which, but you can experiment.) – Steve Summit Nov 29 '22 at 12:38

1 Answers1

1

ncurses provides flexibility for the screen and input.
Link with -lncurses

#include <stdio.h>
#include <ncurses.h>

int main ( void) {
    int ch = 0;
    int row = 0;
    int col = 0;

    initscr ( );
    halfdelay ( 2); // tenths of a second that getch waits for input
    noecho ( );
    getmaxyx ( stdscr, row, col); // max rows and cols
    move ( row / 2, col / 2);
    printw ( "hi");
    refresh ( );
    move ( row / 2, 2);
    printw ( "hello");
    refresh ( );

    move ( row - 3, col / 4);
    printw ( "press enter");
    refresh ( );
    while ( ( ch = getch ( ))) {
        if ( '\n' == ch) {
            break;
        }
    }
    endwin ( );
    return 0;
}

Escape codes are another possibility if your terminal supports them.

#include <stdio.h>

int main ( void) {
    int row = 11;
    int col = 20;

    printf ( "\033[2J"); // clear screen
    printf ( "\033[%d;%dH", row, col);
    printf ( "hi");
    fflush ( stdout);
    printf ( "\033[%d;%dH", row, 2);
    printf ( "hello");
    fflush ( stdout);

    printf ( "\033[%d;%dH", 18, 2);
    fflush ( stdout);
    return 0;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16