Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get optarg as a C++ string object

I am using getopt_long to process command line arguments in a C++ application. The examples all show something like printf("Username: %s\n", optarg) in the processing examples. This is great for showing an example, but I want to be able to actually store the values for use later. Much of the rest of the code uses string objects instead of char* so I need to cast/copy/whatever the contents of optarg into a string.

string bar;
while(1) {
    c = getopt_long (argc, argv, "s:U:", long_options, &option_index);
    if (c == -1) break;
    switch(c)
        {
            case 'U':
                // What do I need to do here to get
                // the value of optarg into the string
                // object bar?
                bar.assign(optarg);
                break;
        }
}

The above code compiles, but when it executes I get an Illegal instruction error if I try to print out the value of bar using printf (it seems to work just fine for cout).

// Runs just fine, although I'm not certain it is actually safe!
cout << " bar: " << bar << "\n";

// 'Illegal instruction'
printf(" bar: %s\n", bar);

I do not know enough about command line debugging to better dig into what the illegal instruction might be. I had been running valgrind, but the sheer volume of memory errors that result from this error have made it difficult for me to pinpoint exactly what might be causing this error.

like image 291
Beau Simensen Avatar asked Jul 13 '26 16:07

Beau Simensen


1 Answers

You told printf that you were suppling a c style string (null terminated array of chars) when specifying %s, but you provided a string class instead. Assuming you are using std::string try:

printf("bar : %s\n", bar.c_str());
like image 91
Trent Avatar answered Jul 16 '26 04:07

Trent