r/C_Programming • u/Treechcer • 11d ago
Question C input that doesn't convert arrow keys to raw escape sequences
When someone was testing my project in C, they pointed out that when they press arrow keys in input it translates them into weird data (eg. ^[[A for up). Is there input in C without ncurses or other libraries that can work in this scenario without causing these issues?
13
Upvotes
38
u/deaddodo 11d ago
Arrow keys are not standard characters, they are control sequences (along with many of the non-character keys on your keyboard). If you want to handle them, you have to use OS-specific functions (termios on Linux, conio's getch on Windows, etc), manually process the sequence (readline+parsing), or use a third-party library that abstracts that out for you (ncurses, as you mentioned).
3
u/[deleted] 11d ago
Standard C input functions are not supposed to handle arrow keys, they are just sending codes. Either use rlwrap on your program, or change your program to use readline.
2
u/ignorantpisswalker 10d ago
Is your terminal in raw input mode?
2
u/Educational-Paper-75 10d ago
In raw input mode you can read escape sequences one character at a time.
1
u/chibuku_chauya 10d ago
Others have mentioned GNU readline. It’s fine but if you don’t care for its size, you can use editline.
1
u/sciencekm 10d ago
This should print the characters that maps to keys.
1
u/yel50 10d ago
that's a Unix convention. Unix clients were assumed to be running on a different machine than the server, so the server didn't have access to raw keyboard events. they came up with the sequences as a way to send control characters across a network.
on modern Unix systems, like Linux, reading the keyboard directly requires root access. that's why GUI programs get raw key events but terminal programs don't. the GUI server, i.e. X windows or Wayland, runs as root, reads the keyboard, and forwards the event to the right application.
so, you either have to do the Unix sequence stuff, run as a GUI instead of command line, require root privileges and read from the keyboard device, or use windows instead of Linux. windows doesn't have the same restrictions and command line apps can still get raw key events.
1
u/0jdd1 10d ago
My first UNIX™ was v6. User-typed characters were buffered until the user hit a new-line equivalent or the ^D character, at which point the next read(1) typically returned the characters typed so far. That’s in cooked mode; raw mode did not buffer characters like this.