Home >Backend Development >C++ >How Can I Parse Command-Line Arguments in C ?
Parsing Command Line Arguments in C
This article explores various methods for parsing command-line arguments in C , providing a detailed analysis and code examples for each approach.
One straightforward method is to utilize the std::find function from the standard library. This approach is suitable for simple command-line options, such as searching for a single-word option (-h for help) or retrieving the file name after the -f argument.
#include <algorithm> char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; }
To enhance this approach, encapsulating these functions within a class can provide added convenience.
class InputParser{ public: InputParser (int &argc, char **argv){ for (int i=1; i < argc; ++i) this->tokens.push_back(std::string(argv[i])); } /// @author iain const std::string& getCmdOption(const std::string &option) const{ std::vector<std::string>::const_iterator itr; itr = std::find(this->tokens.begin(), this->tokens.end(), option); if (itr != this->tokens.end() && ++itr != this->tokens.end()){ return *itr; } static const std::string empty_string(""); return empty_string; } /// @author iain bool cmdOptionExists(const std::string &option) const{ return std::find(this->tokens.begin(), this->tokens.end(), option) != this->tokens.end(); } private: std::vector <std::string> tokens; };
The above is the detailed content of How Can I Parse Command-Line Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!