argparse.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * @file
  3. * @author Caleb Fangmeier <caleb@fangmeier.tech>
  4. * @version 0.1
  5. *
  6. * @section LICENSE
  7. *
  8. *
  9. * MIT License
  10. *
  11. * Copyright (c) 2017 Caleb Fangmeier
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in all
  21. * copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. * SOFTWARE.
  30. *
  31. * @section DESCRIPTION
  32. * \see http://stackoverflow.com/questions/865668/how-to-parse-command-line-arguments-in-c#868894
  33. */
  34. #ifndef argparse_hpp
  35. #define argparse_hpp
  36. #include <algorithm>
  37. #include <string>
  38. #include <vector>
  39. namespace fv::util{
  40. class ArgParser{
  41. private:
  42. std::vector <std::string> tokens;
  43. std::string empty_string;
  44. public:
  45. ArgParser (int &argc, char **argv){
  46. for (int i=1; i < argc; ++i)
  47. this->tokens.push_back(std::string(argv[i]));
  48. }
  49. /// @author iain
  50. const std::string& getCmdOption(const std::string &option) const{
  51. std::vector<std::string>::const_iterator itr;
  52. itr = std::find(this->tokens.begin(), this->tokens.end(), option);
  53. if (itr != this->tokens.end() && ++itr != this->tokens.end()){
  54. return *itr;
  55. }
  56. return empty_string;
  57. }
  58. /// @author iain
  59. bool cmdOptionExists(const std::string &option) const{
  60. return std::find(this->tokens.begin(), this->tokens.end(), option)
  61. != this->tokens.end();
  62. }
  63. };
  64. }
  65. #endif // argparse_hpp