Advertisement
ulfben

command line options parser

Jan 2nd, 2018
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. //(incomplete!) command line options utility
  2. #pragma once
  3. #include <string>
  4. #include <algorithm>
  5. #include <vector>
  6.  
  7. class ProgramOptions{
  8. private:
  9.     const std::string EMPTY{""};
  10.     std::vector<std::string> _tokens;
  11. public:
  12.     ProgramOptions(const int argc, char* argv[]){
  13.         _tokens.reserve(argc);
  14.         for(int i = 0; i < argc; ++i){
  15.             _tokens.emplace_back(argv[i]);
  16.         }
  17.     }
  18.     const std::string& getOption(const size_t index) const{
  19.         if(index >= _tokens.size()){
  20.             return EMPTY;
  21.         }
  22.         return _tokens[index];     
  23.     }
  24.     const std::string& getOption(const std::string& option) const{
  25.         auto itr = std::find(_tokens.begin(), _tokens.end(), option);
  26.         if(itr != _tokens.end() && ++itr != _tokens.end()){
  27.             return *itr;
  28.         }      
  29.         return EMPTY;
  30.     }
  31.     std::string toString() const{
  32.         std::string out;
  33.         static const std::string newLine{"\n"};
  34.         for(const auto& str : _tokens){
  35.             out += str+newLine;
  36.         }
  37.         return out;
  38.     }
  39.     bool optionExists(const std::string& option) const {
  40.         return std::find(_tokens.begin(), _tokens.end(), option) != _tokens.end();
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement