I'm currently working on developing a simple Query language for basic CRUD functions, it is console based and the user will enter a query in the following form:
FIND WHERE NAME nametofind
and the language will search a vector of items and return the item if it's found. I have developed the following for parsing this query.
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;
}
However, there is some serious problems with this it seems... For instance, it currently splits the items by their spaces and then uses them to check what commands are use, but what IF the query to search has spaces in it? e.g.
if(result_items[3] != "")
{
FINDquery(result_items[3]);
}
this works fine the query is
FIND WHERE NAME mynametosearch
but what about when its:
FIND WHERE NAME my name to search
It now has additional params exceeding result_items[3] and the search will fail.
What better approach can i take with this?
while (ss >> token)gets the space separated tokens, you should usevector::size()before indexing into the vector or::at()for each access to avoid undefined behaviour, there's no need to check for empty string elements - your token parsing made sure there wouldn't be any in the vector, you would have noticed that if you'd printed the vector after reading it in - it's a(n obvious ;-P and) useful debugging step.