سؤال

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();
         }
هل كانت مفيدة؟

المحلول 2

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
        }
}

نصائح أخرى

The first string in argv isn't the first command line argument, it's usually the path to the exe. I recommend putting the command line arguments in an easy data structure.

vector<string> args(argv, argv + argc);

Now you can pass the vector to your functions.

Pass parameters to your function:

void file(int * argc, char * * argv)
{
    //
}

int main(int argc, char * * argv)
{
  if (argv[1] == open)
  {
     file(argc, argv);
  }
  return 0;
}

It's not really clear what you're asking. If the goal is to call different functions depending on one of the arguments, the usual solution is to use a map of strings to pointers to functions, and then do something like:

MapType::const_iterator entry = map.find( argv[1] );
if ( entry == map.end() ) {
    std::cerr << "Unknown function " << argv[1] << std::endl;
    returnCode = 1;
} else {
    (*entry->second)();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top