How to check command line arguments in any order

Here is an easy solution to passing parameters to a C++ application from the command line that does not require any external libraries.

Since parameters are read inside a loop, the order in which they are passed is not important.

#include <string>
#include <iostream>

int main(int argc, char* argv[]) {
    for (int i = 1; i < argc; i++) {
        std::string s(argv[i]);
        if (s == "-a") {
            std::cout << "You passed parameter -a" << std::endl;
        } else if (s == "-b") {
            std::cout << "You passed parameter -b" << std::endl;
        } else {
            std::cout << "Unknown: " << s << std::endl;
        }
    }
    return 0;
}

Leave a Reply