Passing std::string as input to getopt()

  argv, c++, getopt

I have a program that basically looks like this:

#include <iostream>
#include <unistd.h> // getopt
#include <vector>
#include <string>
#include <list>
#include <sstream>

using namespace std;

//a parameter structure to store parameters provided through console
typedef struct pairwise_param {
    double alpha;
    double beta;
} param;

//parse the parameter values
void param_getopt(param *pm, int argc, char **argv) {
    int opt;

    while((opt = getopt(argc, argv, "a:b:")) != -1) {
        switch(opt) {
        case 'a':
            pm->alpha  = atof(optarg);
            break;

        case 'b':
            pm->beta   = atof(optarg);
            break;
        }
    }
}

int main(int argc, char* argv[]) {
    //initialize param structure
    param pm;

    //pass command line arguments to param
    param_getopt(&pm, argc, argv);

    //do something to the parameters
    std::cout << "Alpha: " << pm.alpha  << std::endl;
    std::cout << "Beta: " << pm.beta  << std::endl;


    return(0);
}

By making a header file and changing the main function to someother name, e.g. int main(int argc, char* argv[]) -> int maincomp(int argc, char* argv[]) I want to call the new function maincomp() from another program but instead of passing command line arguments I want to pass the arguments through a std::string.

I thought I could do something like this but it does seem to have some issues with getopt() that Im not entirely certain why.

int main(int argc, char* argv[]) {
    //create string and pass it to maincomp
    std::string cmd = "-a2.3 -b3.2";
    std::istringstream ss(cmd);
    std::string arg;
    std::list<std::string> ls;
    std::vector<char*> newargv;

    while (ss >> arg) {
        ls.push_back(arg);
        newargv.push_back(const_cast<char*>(ls.back().c_str()));
    }

    newargv.push_back(0);

    int out = maincomp(newargv.size(), &newargv[0]);

    return(out);
}

The entire code:
https://onlinegdb.com/tjMC-LwiP

Source: Windows Questions C++

LEAVE A COMMENT