Skip to content

Instantly share code, notes, and snippets.

@podborski
Last active July 26, 2019 17:25
Show Gist options
  • Save podborski/3a285f6dbbeee803d59eac631eda618b to your computer and use it in GitHub Desktop.
Save podborski/3a285f6dbbeee803d59eac631eda618b to your computer and use it in GitHub Desktop.
Very simple c++ program options class, In case you don't want to use any libs and just need a very simple parsing stuff.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
class SimpleCmdOptionParser
{
typedef std::vector<std::string> OptList;
public:
SimpleCmdOptionParser(int32_t argc, char** argv)
{
for(int32_t i=1; i<argc; ++i) m_strOptions.push_back(std::string(argv[i]));
}
bool isSet(std::string strOpt)
{
return std::find(m_strOptions.begin(), m_strOptions.end(), strOpt) != m_strOptions.end();
}
std::string getOption(std::string strOpt, std::string strDefault=std::string())
{
std::string strRet;
if(isSet(strOpt))
{
OptList::iterator it = std::find(m_strOptions.begin(), m_strOptions.end(), strOpt); it++;
if(it != m_strOptions.end()) { if((*it)[0] != '-') { strRet = *it; } }
}
if(strRet.empty() && !strDefault.empty()) { strRet = strDefault; }
return strRet;
}
private:
OptList m_strOptions;
};
int main(int argc, char** argv)
{
// options
SimpleCmdOptionParser cOptions(argc, argv);
std::string strInputFile;
std::string strOutputFile = "out.265";
if(cOptions.isSet("-h")) // just check if value was set
{
std::cout << "Some help message...\n"
" -h this help text\n"
" -i inputFile input file\n"
" -o outputFile output file (default: " << strOutputFile << ")\n" << std::endl;
return 0;
}
strInputFile = cOptions.getOption("-i"); // get value
strOutputFile = cOptions.getOption("-o", strOutputFile); // get value with some default value set
std::cout << "in = " << strInputFile << std::endl;
std::cout << "out = " << strOutputFile << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment