c++获取终端命令行的输入字符串,常用方法有std::getline和linux库函数readline。cin和scanf也可以得到终端命令行的输入,但是其遇到空间就会结束,不是特别的好用。而std::getline和readline 不会忽略space、tab,遇到Enter才会结束,可适用大部分场景。
readline的使用需要注意以下几点:
- 需要先check下自己的linux系统是否安装了readline库,如果没有安装,ubuntu上执行sudo apt-get install libreadline-dev;centos上执行sudo yum install readline-devel
- readline() 的参数是一个字符串,调用函数的时候会在屏幕上输出,这个函数会读取一行输入,然后返回一个指向输入字符串的指针,readline 会为输入的字符串动态分配内存,所以使用完之后需要free掉。
- 由于readline是一个动态库,编译的时候需要加上 -lreadline,不然会找不到相关的函数。并且,如果是直接g++命令行编译的,需要将-lreadline写在编译命令行的最后。
std::getline 参考 https://blog.csdn.net/qq_43213352/article/details/106479895
readline官方手册 https://man7.org/linux/man-pages/man3/readline.3.html
readline的简单使用,参考 https://blog.csdn.net/xuancbm/article/details/81436681
//sudo apt-get install libreadline-dev
//g++ -std=c++11 -g xxx.cpp -o xxx -lreadline
//if use "g++ -std=c++11 -lreadline -g xxx.cpp -o xxx", will build error
#include <iostream>
#include <readline/readline.h>
#include <readline/history.h>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
std::string cmd;
#if 0
for(int i = 0 ; i < 100; ++ i)
{
char* buf = readline("[cmd] >> "); // can input space, stop when encounter Enter key '\n'
cmd = buf;
free(buf); //must free here
bool is_all_spaces = cmd.find_first_not_of(' ') == std::string::npos;
if ((!is_all_spaces) && (cmd.size() > 0))
{
add_history(cmd.c_str());
}
else if (history_get(where_history()) != NULL)
{
cmd = history_get(where_history())->line;//get last command
}
else
cmd = "";
cout<<"cmd["<<i<< "] : "<< cmd <<endl;
}
#endif
#if 1
std::string last_cmd ;
for(int i = 0 ; i < 100; ++ i)
{
cout<<"[cmd] >> " ; // can input space, stop when encounter Enter key '\n'
std::getline(std::cin, cmd);
if(cmd != "")
{
last_cmd = cmd;
}
else
{
cmd = last_cmd;
}
cout<<"cmd["<<i<< "] : "<< cmd <<endl;
}
#endif
return 0;
}