81
votes

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 scanf().
  • Analyze the string and calculate.

But something weird happens. When I try to move the cursor, it prints four characters:

  • pressing Up prints "^[[A"
  • pressing Dn prints "^[[B"
  • pressing Rt prints "^[[C"
  • pressing Lt prints "^[[D"

  • How can this be avoided?

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

5
Special characters like ^U and Backspace will work because the keyboard driver handles those. But the arrow key behavior you're used to is programmed into the shell. When you write your own program, you have to handle it yourself, or you could install rlwrap and run your program as rlwrap my_prog and it will do what you expect. The characters you see are the escape sequences generated by those key presses.lurker
Those are the traditional ANSI escape sequences which represent those cursor keys. See stackoverflow.com/questions/4130048/…keshlam
This answer on unix.stackexchange may help, it helped me understand the issue.A1rPun
In Ubuntu if yout just need a posix shell, you can use set -o posix or --posix to force the default shell into compliance. Dash is not compiled for interactive use.Ray Foss

5 Answers

35
votes

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?

22
votes

For those who are coming from the osx (mac) try changing the shells to bash

Terminal -> Preferences -> Shells open with -> [select] Command (complete path)

then paste

/bin/bash

13
votes

This might be because the user account is created in shell. You can change it to bash by two ways.

Permament solution is -

sudo chsh -s /bin/bash ${username}

To get this solution working you will have to logout and login

Temporary solution is everytime when you login into the ubuntu server type bash and hit return.

0
votes

On MacOS Terminal for me was enough to uncheck "Scroll alternate screen" for the issue to disappear. See screenshot of the preferences below.enter image description here

-5
votes

i think simple way is we can just do kill %% because this sometimes happen because of background processes.