Kevin Dong Kevin Dong - 1 year ago 69
C Question

Why the terminal shows "^[[A" "^[[B" "^[[C" "^[[D" when pressing the arrow keys in Ubuntu?

I've written a tiny program in Ansi C on Windows first, and I compiled it on Ubuntu with the built-in GCC now.

The program is simple:

  • read the line from console with

  • Analyze the string and calculate.

But something weird happened, when I want to move the cursor, it'll add four characters:

  • press Up will be "^[[A"

  • press Dn will be "^[[B"

  • press Rt will be "^[[C"

  • press Lt will be "^[[D"

  • How to avoid this?

  • Why it will print the 4 characters instead of moving cursor?

Answer Source

Because that's what the keyboard actually sends to the PC (more precisely, what the terminal prints for what it actually receives from the keyboard). bash for example gets those values, deciphers them and understands that you want to move around, so it will either move the cursor (in case of left/right) or use its history to fetch previous commands (up/down). So you can't expect your program to magically support arrow keys.

However, reading from standard input from the terminal already supports left/right arrow keys (I believe, but I'm not in Linux right now to test and make sure). So my guess is that there is another issue interfering. One possible cause could be that one of your modifier keys is stuck? Perhaps ALT, CTRL or SUPER?