Reputation: 672
When dealing with console input (stdin,std::cin) is there a portable way in C++ to manage the various actions that a user may perform like:
For example in windows when using std::cin (eg: std::cin >> s;), it allows for arrow keys, however when using the same bit of code on linux, the arrow keys are assumed as part of the input, the cursor is not moved around.
I know of various TUI frameworks like curses and ncurses that provide such functionality however they are more than what is required.
I'm hoping there's a simple solution based on the standard libraries, or even a lightweight open source library that might have a std::getline like feature that is portable across the more popular OSes.
Upvotes: 1
Views: 823
Reputation: 4236
readline is a good choice for Linux, but it's GPL! I use the following code to compile on Windows and Linux:
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
...
void getline(char *buf)
{
#ifdef USE_READLINE
char *tmp;
tmp = readline(PROMPT);
if(strncmp(tmp, buf, MAXLENGTH)) add_history(tmp); // only add new content
strncpy(buf, tmp, MAXLENGTH);
buf[MAXLENGTH]='\0';
free(tmp);
#else
std::cout<<PROMPT;
std::cin.get(buf,MAXLENGTH);
std::cin.ignore(); // delete CR
#endif
}
Upvotes: 0
Reputation: 154027
Things like backspace and delete are typically handled by the system; when you read from a terminal, you only get the input when the user presses enter.
What the system does is usually fairly limited. In particular,
I don't know of any that do things like file name completion.
If more than what the system does is desired, I would recommend
looking into the readline
library, used by many GNU programs
(bash, gdb, etc.). It's available separately from the
applications which use it. (Two small warnings: I don't know
how good its support is for native Windows, and I'm not sure
which license it is under: GPL or LGPL.)
Upvotes: 1