Search code examples
c++functionvoidargvargc

Assigning command line arguments to functions


Lets say I wanted to open a function (it opens a file, does something with it, then spits out the results to a different file). Using argv and argc, and from going through all the tutorials online, I'm assuming that if i print argv[0] i get the file name. My question is how do i set lets say the next argv[1.2.n] to a function. So if the user were to type in open (after the user is in the program directory), it would open that function. Something like:

  void file();

...

  if (argv[1] == open){
            file();
         }

Solution

  • argv is of type char*[] (array of char* pointers). You cannot directly compare string constants (type char*), which you need to quote. Instead, I suggest you to convert it to a c++ string type:

    #include <string>
    
    void file(){   
         // ...
    }
    
    int main(int argc, char *argv[]) {
            if(argc>=2)
            {
                    if(std::string(argv[1]) == "open")
                    {
                            file();
                    }
    
            }
            else
            {
                    // print usage
            }
    }