How to create command history in a console application?

I want to create an interactive console application that allows you to enter a command in a loop. For example, the user types โ€œsearchโ€ and the program find some data and print it on the screen. Then the program waits for the next command (which may be a search, exit, or other). For the convenience of users, I want my program to support the history of commands (for example, in the terminal, by pressing the up and down arrows on the keyboard). But I canโ€™t understand how to do this because I donโ€™t know how to print text that can be read further scanf, std :: getline, std :: cin, etc. Therefore, the code std::cin << "hello"; not compiled (no match for 'operator <in' std :: cin <"hello"). Function fprintf(stdin, "hello"); nothing prints, and scanf cannot read this printed message. Obviously, std::getline(std::cin, str); and scanf("%s", s); and gets(s) etc. Cannot read text that was issued by printf or std::out . So the question is: how can I print text on the console, which will also be in stdin ( std::cin )? Or maybe a more elegant way to organize team history?

PS I also thought about simulating a button click to print the text I need, but I hope the best way to make a history of commands

PPS I use Linux and C ++

+4
source share
2 answers

Use readline and history libraries that are made specifically for this purpose.

+3
source

If you do not want to use a library similar to the one proposed by Kerrek SB, you might think in a different direction:

1) What teams should be in history? โ†’ All 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 (for example, start a search when the user enters โ€œsearchโ€)

In addition to step 3, you can simply save the commands that the user enters internally (for example, in some form). If now your user wants to use the command history and presses the up (or down) key, you simply view the corresponding command in your internal vector. Then he presses 'enter'? Just process the command, the user selected from your internal command history.

+1
source

Source: https://habr.com/ru/post/1499558/


All Articles