0

I have made a decent console application in C. The issue is that arrow keys print an escape sequence to the input instead of moving the cursor or navigating previous input. On Windows it works well (same behavior of command prompt).

How can I pull the same thing on Linux?

td211
  • 103
  • 2
  • 5
  • Does this answer your question? [How to make arrow keys and backspace work correctly when asking input from user in C program using termios.h?](https://stackoverflow.com/questions/26615045/how-to-make-arrow-keys-and-backspace-work-correctly-when-asking-input-from-user) – JASLP doesn't support the IES Aug 26 '21 at 07:18
  • This may help: https://stackoverflow.com/questions/10463201/getch-and-arrow-codes – mokumus Aug 26 '21 at 07:27
  • Look into `readline` or its competitors. – Shawn Aug 26 '21 at 07:46
  • Isn't getch() a blocking function? Will it read the arrow keys without pressing enter? – td211 Aug 26 '21 at 12:32

1 Answers1

0

The C++ programming language is made to be a very efficient language. As such, the language itself (i.e. without including any libraries) can't really do that much, basically you can only get input through argc and argv and you can only send output through the return value.

The standard library helps a lot, giving us access things such as files, allowing us to do a lot more. As console developers it also allows us to use the standard input and the standard output through std::cin and std::cout (also the standard error stream through std::cerr but we usually hope nothing will be written to it). Since we get access to those tools through streams, to our program there's no such thing as "The second line from the top of the console", it's only a long line of letters. As such it's absolutely impossible to do this using only C++ and the standard library.

What about windows then? It can do it! Yes, but that's a windows thing, not a C++ thing (it's being a while since I used windows but I remember it sometimes causing issues with streams), third-parties windows-compatible console emulators can function exactly like Linux terminals (and I guess Linux terminals could work just like windows, I just haven't seen one yet) so we need something to guaranty us this behavior.

Thankfully, one of the main advantage of C/C++ is the sheer number of libraries available to us. An big part of C++ programs don't even use a console anymore, bypassing completely the issue.

What I'd recommend is to find a good library (I sometimes use ncurses although I think it's Linux-only and probably a bit too feature full for your usecase) and use it to control the cursor to make it do what you want

Tzig
  • 726
  • 5
  • 20
  • 1
    I have been thinking to use ncurses when I get most features done. Ncurses doesn't seem to have the latest version on windows. – td211 Aug 26 '21 at 12:37
  • 1
    I ended up using readline() and write a simple readline() function for windows compatibility. – td211 Mar 15 '22 at 19:29