user2717575
user2717575

Reputation: 409

How to make command history in console application?

I want to make interactive console application, which allows to enter command in loop. For example, user types "search" and program finds some data and prints it on the screen. Then the program waits for the next command (which can be search, quit or other). For user's convenience I want my program supports command history (like in terminal, when pressing up and down arrow on the keyboard). But I can't realize how to do that because I don't know how to print text which can be read further by scanf, std::getline, std::cin and so on. So code std::cin << "hello"; isn't compiled (no match for ‘operator<<’ in ‘std::cin << "hello"’). Function fprintf(stdin, "hello"); prints nothing and scanf can't read this printed message. It is evident that std::getline(std::cin, str); and scanf("%s", s); and gets(s) and so on can't read text which has been outputted by printf or std::out. So the question is: how can I print text on console which also will be in stdin (std::cin)? Or maybe there is more elegant way to organize command history?

P.S. I also thought about simulating of button pressing to print the text I need, but I hope there is better way to make command history

P.P.S. I use Linux and C++

Upvotes: 6

Views: 4160

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

Use the readline and history libraries, which are made exactly for that purpose.

Upvotes: 3

sebi
sebi

Reputation: 431

If you don't want to use a library like those Kerrek SB suggested, you might think in another direction:

1) What commands should be in the history? -> All the commands, the user typed. 2) How do you know, what the user typed? -> You get it from std::in 3) What do you do with the commands, you get from std::in? -> You process them (e.g. start a search when the user typed 'search')

Additionally to step 3 you can just store the commands a user typed internally (e.g. in some kind of vector). If now your user wants to use the command history and presses 'key up' (or 'key down') you just look up the corresponding command in your internal vector. He presses 'enter' afterwards? Just process the command, the user selected from your internal command-history.

Upvotes: 1

Related Questions