我目前正致力于为基本CRUD功能开发一种简单的查询语言,它基于控制台,用户将以下列形式输入查询:
FIND WHERE NAME nametofind
并且语言将搜索项目向量并返回项目(如果已找到)。我已经开发了以下内容来解析这个查询。
int SDIQL::parseQuery(std::string query)
{
std::vector<std::string> result_items;
std::istringstream ss(query);
std::string token;
while(std::getline(ss, token, ' ')) {
//std::cout << token << '\n';
result_items.push_back(token);
}
if(result_items[0] == "ADD" || result_items[0] == "INSERT")
{
if(result_items[1] != "")
{
if(result_items[2] == "WITH")
{
if(result_items[3] != "")
{
ADDquery(result_items[1], result_items[3]);
}
else
{
std::cout<<"No value entered, please try again."<<std::endl;
}
}
else
{
std::cout<<"Invalid paramater entered, expected WITH, please try again."<<std::endl;
}
}
else
{
std::cout<<"No Key Specified, please try again."<<std::endl;
}
}
else if(result_items[0] == "FIND" || result_items[0] == "GET")
//FIND WHERE NAME name
{
if(result_items[1] == "WHERE")
{
if(result_items[2] == "NAME")
{
if(result_items[3] != "")
{
FINDquery(result_items[3]);
}
else
{
std::cout<<"No value entered, please try again."<<std::endl;
}
}
else
{
std::cout<<"Invalid paramater entered, expected NAME, please try again."<<std::endl;
}
}
else
{
std::cout<<"Invalid paramater entered, expected WHERE, please try again."<<std::endl;
}
}
else if(result_items[0] == "DELETE" || result_items[0] == "REMOVE")
{
if(result_items[1] == "WHERE")
{
if(result_items[2] == "NAME")
{
if(result_items[3] != "")
{
DELETEquery(result_items[3]);
}
else
{
std::cout<<"No value entered, please try again."<<std::endl;
}
}
else
{
std::cout<<"Invalid paramater entered, expected NAME, please try again."<<std::endl;
}
}
else
{
std::cout<<"Invalid paramater entered, expected WHERE, please try again."<<std::endl;
}
}
return 1;
}
然而,这似乎有一些严重的问题...例如,它当前按空格分割项目,然后使用它们来检查使用的命令,但是如果搜索的查询在其中有空格? e.g。
if(result_items[3] != "")
{
FINDquery(result_items[3]);
}
这样可以正常查询
FIND WHERE NAME mynametosearch
但是什么时候:
FIND WHERE NAME my name to search
现在它有超过result_items [3]的额外参数,搜索将失败。
我可以采取哪种更好的方法?
答案 0 :(得分:1)
由于您自己开发语言,因此您应该能够写下您语言的语法。如果不是,你应该考虑这样做 因为只要你有语法,就可以使用你想要的任何解析器库。我个人觉得boost::spirit非常好。但是好的旧的flex / bison组合也应该这样做。