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.