From 95c77095e38e175746cd458a4c4f4ba21d6fda4f Mon Sep 17 00:00:00 2001 From: HuangZonghao Date: Fri, 29 Apr 2022 00:45:45 -0400 Subject: [PATCH] Parse command line input wrapped in a string This is the simplest implementation of the functionality described in the short description. This patch only deals with the arguments seperated by whitespaces, and process them as is, without any shell processing like expanding wildcards or replacing variables. --- include/cxxopts.hpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index b957956..959f2f1 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1772,6 +1772,9 @@ namespace cxxopts ParseResult parse(int argc, const char* const* argv); + ParseResult + parse(std::string argv_str); + OptionAdder add_options(std::string group = ""); @@ -2284,6 +2287,30 @@ Options::parse(int argc, const char* const* argv) return parser.parse(argc, argv); } +inline +ParseResult +Options::parse(std::string argv_str) +{ + std::vector tokens; + std::string token; + std::istringstream iss(argv_str); + while (std::getline(iss, token, ' ')) + { + tokens.push_back(token); + } + + const char** argv = new const char*[tokens.size()]; + for (int i = 0; i < tokens.size(); ++i) { + argv[i] = tokens[i].c_str(); + } + + OptionParser parser(*m_options, m_positional, m_allow_unrecognised); + + auto parse_result = parser.parse(tokens.size(), argv); + delete argv; + return parse_result; +} + inline ParseResult OptionParser::parse(int argc, const char* const* argv) {