Created
December 6, 2014 13:20
-
-
Save kolodziej/f239fe94620174e82ab7 to your computer and use it in GitHub Desktop.
Cmdline parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <sstream> | |
#include <vector> | |
using namespace std; | |
class Parser | |
{ | |
private: | |
char delimiter, quote, escape; | |
public: | |
Parser(char _delimiter, char _quote, char _escape) : | |
delimiter(_delimiter), | |
quote(_quote), | |
escape(_escape) | |
{} | |
vector<string> parse(string command) | |
{ | |
vector<string> tokens; | |
stringstream token; | |
bool escapeNext = false; | |
bool quoteMode = false; | |
for (string::iterator it = command.begin(); it != command.end(); ++it) | |
{ | |
if (*it == escape && escapeNext == false && quoteMode == false) | |
{ | |
#ifdef DEBUG | |
clog << "--- escaping next\n"; | |
#endif | |
escapeNext = true; | |
} else if (*it == delimiter && escapeNext == false && quoteMode == false) | |
{ | |
#ifdef DEBUG | |
clog << "--- delimiter\n"; | |
#endif | |
if (token.str().empty() == false) | |
{ | |
tokens.push_back(token.str()); | |
token.str(string()); | |
} | |
} else if (*it == quote && escapeNext == false) | |
{ | |
#ifdef DEBUG | |
clog << "--- quoteMode = " << !quoteMode << "\n"; | |
#endif | |
quoteMode = !quoteMode; | |
} else | |
{ | |
#ifdef DEBUG | |
clog << "input: " << *it << " (escape: " << escapeNext << ", quote: " << quoteMode << ")\n"; | |
#endif | |
token << *it; | |
escapeNext = false; | |
} | |
} | |
if (token.str().empty() == false) | |
{ | |
tokens.push_back(token.str()); | |
} | |
return tokens; | |
} | |
}; | |
int main() | |
{ | |
string command; | |
getline(cin, command); | |
Parser parser(' ', '\"', '\\'); | |
auto tokens = parser.parse(command); | |
for (auto it = tokens.begin(); it != tokens.end(); ++it) | |
{ | |
cout << *it << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment