-5

I'm encountering a problem trying to use char** argv from the main. My goal is to use argv[2] to pass to a string in another class called Game. Does someone have an idea how I can use argv and pass it as a string to another class?

int main(int argc, char **argv)
{
  Game game(argv[2]);
  game.runsecondmethod();
}

And in Game.cpp:

Game::Game(std::string a)
{
   write.filename = a;
}
error, no match for call to (Game)(char*&)
Biffen
  • 6,249
  • 6
  • 28
  • 36
Erry07
  • 29
  • 1
  • 2
  • 5
  • 1
    You can't pass an array of pointers to char to some class as a string. – ForceBru May 29 '15 at 10:23
  • 4
    Can you edit your question to include the code you are having problems with? – Lewis Norton May 29 '15 at 10:24
  • A common way of writing the type of `argv` is `char* argv[]`. This way you can easily see that you can write `argv[2]` to access the second argument of your program, which you can then convert into an `std::string` using one of its constructors. Note that `argv[0]` stores the name your program was started with. – Alexander Weinert May 29 '15 at 10:26
  • `Game game(std::string(argv[2]));` – simon May 29 '15 at 10:33
  • 2
    @Erry07 The code you showed should compile. Could you show the full text of the error mesage? Also check whether constructor Game(std::string a) is declared inside the class definition. – Vlad from Moscow May 29 '15 at 10:40
  • The code you posted works fine for me. – Galik May 29 '15 at 10:54

1 Answers1

1

You haven't actually provided code that exhibits your problem but, to answer your question, ways to pass argv[2] as a string to a function include

  #include <cstring>
  #include <iostream>
  void func(const char *s)
  {
       //  treat s as a zero terminated string

       if (std::strcmp(s, "Hello") == 0)
       {
            std::cout << "You said hello\n";
       }
  }

  int main(int argc, char **argv)
  {
      if (argc >= 3)
        func(argv[2]);
      else
         std::cout << "You have not supplied an argv[2]\n";
  }

or

  #include <string>
  #include <iostream>
  void func2(const std::string &s)
  {
       if (s == "Hello")
       {
            std::cout << "You said hello\n";
       }
  }

  int main(int argc, char **argv)
  {
      if (argc >= 3)
        func2(argv[2]);
      else
         std::cout << "You have not supplied an argv[2]\n";
  }

The first example above (apart from usage of std namespace, std::cout and C++ headers) is essentially vanilla C.

The second example uses the std::string class, so comparison of strings is possible using the == operator. Note that main(), when calling func2() implicitly converts argv[2] into an std::string (since std::string has a constructor that permits that conversion) that is then passed to the function.

In both cases, main() checks argc to ensure that 2 (or more) arguments have been passed to it.

Peter
  • 35,646
  • 4
  • 32
  • 74