0

I receive from another method a string (I don’t know the size of this) and I want to fill my argv (and get argc) with this string to pass to other method and I don’t know how to do it.

At the start of the string I set the name of my app so I have a final string like:

"myapp arg1 arg2 arg3 arg4"

The code I have is the following:

int main (int argc, const char* argv[])
{

    while(true)
    {

        // send_string() give a string like: “the_name_of_my_app arg1 arg2 arg3 arg4”
        std::string data = send_string(); 

        argv = data;
        argc = number_of_element_on_data;

        other_function(argc, argv);
    }
    return 0;
}
skualo_
  • 3
  • 2
  • 3
    You can call `other_function` with any `int` and `char* []` variable, you don't have to (and probably shouldn't) overwrite `argc` and `argv` – UnholySheep Oct 22 '21 at 20:52
  • `argc` and `argv` should be considered read-only. They don't belong to you. Declare your own `int` and `char* []` variables and put your content there instead, and pass those to `other_function`. – Ken White Oct 22 '21 at 20:56

1 Answers1

0

Try something like this:

#include <vector>
#include <string>
#include <sstream>

int main (int argc, const char* argv[])
{
    while (true)
    {
        // send_string() give a string like: “the_name_of_my_app arg1 arg2 arg3 arg4”
        std::string data = send_string(); 

        std::istringstream iss(data);
        std::string token;

        std::vector<std::string> args;
        while (iss >> token)
            args.push_back(token);

        std::vector<const char*> ptrs(args.size()+1);
        for(size_t i = 0; i < args.size(); ++i)
            ptrs[i] = args[i].c_str();
        ptrs[args.size()] = NULL;

        other_function(args.size(), ptrs.data());
    }
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770