我正在使用getopt_long來處理C++應用程序中的命令行參數。這些例子在處理例子中都顯示出類似printf("Username: %s\n", optarg)
的東西。這對於展示一個示例非常有用,但我希望能夠實際存儲這些值供以後使用。其餘大部分代碼使用string
對象而不是char*
,因此我需要將optarg的內容轉換/複製到字符串中。將optarg作爲C++字符串對象獲取
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;
}
}
上面的代碼編譯,但是當它執行我得到一個錯誤Illegal instruction
如果我嘗試打印出用printf酒吧的值(它似乎只是正常工作的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,但是由於這個錯誤導致的大量內存錯誤使我很難精確地確定可能導致這個錯誤的原因。
我想我必須把它放在我要記住的重要事情列表中。謝謝! – 2009-03-06 01:16:12