0
我目前正在開發的基本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;
}
然而,有一些嚴重的問題,這似乎...例如,它目前由他們的空間分割的項目,然後用它們來檢查哪些命令是使用,但如果查詢搜索有空格嗎?例如
if(result_items[3] != "")
{
FINDquery(result_items[3]);
}
能正常工作的查詢是
FIND WHERE NAME mynametosearch
但什麼時候它:
FIND WHERE NAME my name to search
它現在有更多的PARAMS超過result_items [3]和搜索將失敗。
我可以採取什麼更好的方法呢?
有幾件事:只要'while(ss >> token)'得到空格分隔的標記,你應該在每個訪問的索引之前使用'vector :: size()'索引到vector或':: at()'爲了避免未定義的行爲,不需要檢查空字符串元素 - 您的令牌解析確保向量中沒有任何內容,您會注意到,如果您在閱讀完矢量後打印了該向量,則它是( n明顯; -P和)有用的調試步驟。 –