3

I want to write a command line shell for a background program, and in witch I can type some commands. I want to add a feature like the bash (or other shell-like) ---'UP' key to get the historic input. How can I capture the 'UP' key was pressed?

If I just use std::getline(std::cin, line) I can't get the 'UP' key or other function key, ie. Ctrl+w to delete a word of the input line.

superK
  • 3,932
  • 6
  • 30
  • 54
  • 1
    There is a "getline library", which is a set of C functionality that allow you to edit/record history/etc on the input for your program. Alternatively, you will have to read raw input and handle keyboard input yourself... – Mats Petersson Aug 29 '13 at 10:56
  • There was a [related (though different) question](http://stackoverflow.com/questions/18505947/how-to-make-command-history-in-console-application/18506211#18506211) today, which might be of interest. – Hulk Aug 29 '13 at 11:02
  • @MatsPetersson Your suggestion is very useful, it should be an answer rather than a commant. I use GNU readline library now. http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html – superK Aug 29 '13 at 12:18

3 Answers3

4

There is a readline function that supports history and line editing, etc.

In basic mode it does reading of line, etc. If you want to add hooks, you can make it expand commands when pressing tab or similar.

This is what your typical shell in Linux uses.

Documentation here: http://web.mit.edu/gnu/doc/html/rlman_2.html

An example here: http://www.delorie.com/gnu/docs/readline/rlman_48.html

Main project page: http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

Use kbhit() to get Keyboard Arrow Keys

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
  • Does it work for all compilers? [see](http://www.cprogramming.com/fod/kbhit.html) – cpp Aug 29 '13 at 11:08
0

Use ncurses library, see sample program:

#include<ncurses.h>
#include<iostream>

int main()
{
    int ch;
    initscr();  //initialize the ncurses data structures

    keypad(stdscr,TRUE); //enable special keys capturing

    ch=getch();

    if(ch==KEY_UP)
        std::cout << "Key up pressed!" << std::endl;
}
cpp
  • 3,743
  • 3
  • 24
  • 38