【发布时间】:2009-03-06 00:52:08
【问题描述】:
我正在使用 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;
}
}
上面的代码可以编译,但是当它执行时,如果我尝试使用 printf 打印 bar 的值,我会得到一个 Illegal instruction 错误(它似乎对 cout 工作得很好)。
// Runs just fine, although I'm not certain it is actually safe!
cout << " bar: " << bar << "\n";
// 'Illegal instruction'
printf(" bar: %s\n", bar);
我对命令行调试知之甚少,无法更好地挖掘非法指令可能是什么。我一直在运行 valgrind,但由于此错误导致的大量内存错误使我很难准确找出可能导致此错误的原因。
【问题讨论】:
标签: c++ string getopt getopt-long