[Solved] C++ program flags [closed]


int main(int argc, const char* argv[]) {
    for(int i = 0; i < argc; ++i) {
        // argv[i] contains your argument(s)
    }
}

Some more details:

Accepting arguments passed to your program can be done by adding two arguments to main: One int, which is assigned the number of arguments you give to your program, and one const char* [], which is an array of C strings.

One example: Say you have a program main which should react to the arguments apple and orange. A call could look like this: ./main apple orange. argc will be 3 (counting “main”, “apple”, and “orange”), and iterating through the array will yield the 3 strings.

// executed from terminal via "./main apple orange"
#include <string>
int main(int argc, const char* argv[]) {
    // argc will be 3
    // so the loop iterates 3 times
    for(int i = 0; i < argc; ++i) {

        if(std::string(argc[i]) == "apple") {
            // on second iteration argc[i] is "apple" 
            eatApple();
        }

        else if(std::string(argc[i]) == "orange") {
            // on third iteration argc[i] is "orange" 
            squeezeOrange();
        }

        else { 
            // on first iteration argc[i] (which is then argc[0]) will contain "main"
            // so do nothing
        }
    }
}

This way you can perform tasks according to the application arguments, if you only want to squeeze an orange, just give one argument, like ./main orange.

1

solved C++ program flags [closed]