[Solved] Using int main(int argc, char **argv) in c++ [closed]


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.

solved Using int main(int argc, char **argv) in c++ [closed]