0

Currently I discovered that I can move the cursor in the terminal output as if I'm writing in Word using "\033[A" to move the cursor in the line above and "\033[B" to below . So I tried to understand something more and I wrote these 2 lines of code in C :

#include <stdio.h>
#include <stdlib.h>
int main (){
printf("\n 2 3 \033[A \033[D 1 \033[B \n 4 5 6");
}

And this is the output :

      1 
 2 3
 4 5 6

My expectations were differents because this was my expected output

1
2 3
4 5 6

So I'm missing some informations and I think that probably I need of a character that says "go back of one positions" like "\t" but the opposite. I found this page in some old posts Here

But some characters don't work. Can someone explain me how these stuffs work? Because I tried "\033[C" and "\033[D" to move right and left but nothing.

feded
  • 109
  • 2
  • 13
  • The [ASCII](http://www.asciitable.com/) table may help to identify some of the characters you are looking for. `\b` ( binary `10`, octal `\010`) is backspace for example. I ran your exact code by the way and got something a little different. – ryyker Mar 17 '20 at 12:10
  • Does this [question/answers](https://stackoverflow.com/questions/33025599/move-the-cursor-in-a-c-program/33316428) help? (you may not like the answers.) – ryyker Mar 17 '20 at 12:22
  • Nice technical reference [VT100 User Guide](https://vt100.net/docs/vt100-ug/chapter3.html) – David C. Rankin Mar 17 '20 at 16:21

1 Answers1

2

These sequences are called ANSI Escape Sequences, and date back to the 1970s with the DEC VT-100 terminal, so they're still sometimes called VT-100 escape sequences. There's a list here and here.

The codes you're interested in are:

Esc[ValueA  Move cursor up n lines  CUU
Esc[ValueB  Move cursor down n lines    CUD
Esc[ValueC  Move cursor right n lines   CUF
Esc[ValueD  Move cursor left n lines    CUB

One thing you may not be accounting for is that these motions don't care "how much information" is on a given line; they just treat the screen as a grid of characters. So ESC[A goes straight up one line, even if it's "past the end" of the previous line. And so on.

So to move up one line and left two characters:

printf("\033[A\033[2D");

\033 is the ASCII code for ESC (in octal -- sometimes you'll see it in hex as \x1b; same thing). Don't add any extra spaces or newlines; just print the codes directly.

GaryO
  • 5,873
  • 1
  • 36
  • 61