Bea*_*sen 2 c++ string getopt getopt-long
我使用getopt_long来处理C++应用程序中的命令行参数.这些示例都显示printf("Username: %s\n", optarg)了处理示例中的内容.这非常适合展示一个示例,但我希望能够实际存储这些值以供以后使用.其余大部分代码都使用string对象而不是char*我需要将optarg的内容转换/复制到字符串中.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码编译,但是当它执行时我得到一个Illegal instruction错误,如果我尝试使用printf打印出bar的值(它似乎对cout工作正常).
// Runs just fine, although I'm not certain it is actually safe!
cout << " bar: " << bar << "\n";
// 'Illegal instruction'
printf(" bar: %s\n", bar);
Run Code Online (Sandbox Code Playgroud)
我不太了解命令行调试,以便更好地了解非法指令可能是什么.我一直在运行valgrind,但是由于这个错误导致的大量内存错误使我很难确切地指出可能导致此错误的原因.
你告诉printf你在指定%s时提供了ac样式字符串(空终止字符数组),但是你提供了一个字符串类.假设您正在使用std :: string尝试:
printf("bar : %s\n", bar.c_str());
Run Code Online (Sandbox Code Playgroud)