Search code examples
c++linuxconsoleterminal

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


Solution

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