将optarg作为C ++字符串对象获取
-
03-07-2019 - |
题
我使用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的值(它似乎对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,但是由于这个错误导致的大量内存错误使我很难确切地指出可能导致此错误的原因。
解决方案
你告诉printf你在指定%s时提供了c样式字符串(空终止字符数组),但是你提供了一个字符串类。假设你正在使用std :: string试试:
printf("bar : %s\n", bar.c_str());
其他提示
printf()
无法处理C ++ string
。改为使用 bar.c_str()
。
cout << " bar: " << bar << "\n";
非常安全。是什么让你觉得它可能不是?
不隶属于 StackOverflow