Home >Backend Development >C++ >How Can I Parse Command-Line Arguments in C ?

How Can I Parse Command-Line Arguments in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 03:36:09519browse

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 &amp; option)
{
    char ** itr = std::find(begin, end, option);
    if (itr != end &amp;&amp; ++itr != end)
    {
        return *itr;
    }
    return 0;
}

bool cmdOptionExists(char** begin, char** end, const std::string&amp; 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 &amp;argc, char **argv){
            for (int i=1; i < argc; ++i)
                this->tokens.push_back(std::string(argv[i]));
        }
        /// @author iain
        const std::string&amp; getCmdOption(const std::string &amp;option) const{
            std::vector<std::string>::const_iterator itr;
            itr =  std::find(this->tokens.begin(), this->tokens.end(), option);
            if (itr != this->tokens.end() &amp;&amp; ++itr != this->tokens.end()){
                return *itr;
            }
            static const std::string empty_string("");
            return empty_string;
        }
        /// @author iain
        bool cmdOptionExists(const std::string &amp;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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn