Skip to content

Instantly share code, notes, and snippets.

@kolodziej
Created December 6, 2014 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolodziej/f239fe94620174e82ab7 to your computer and use it in GitHub Desktop.
Save kolodziej/f239fe94620174e82ab7 to your computer and use it in GitHub Desktop.
Cmdline parser
#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