Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++

like image 571
user2717575 Avatar asked Oct 04 '22 02:10

user2717575


1 Answers

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

like image 139
Kerrek SB Avatar answered Oct 12 '22 10:10

Kerrek SB