2012-07-13 142 views
0

我试图在我的代码中实现命令行选项。出于某种原因,我的-a选项可以正常工作,但我的-c选项无法正常工作,即使它们基本相同。当我尝试使用-c选项运行我的代码时,我收到以下消息。命令行参数问题

terminate called after throwing an instance of 'std::logic_error' 
what(): basic_string::_S_construct NULL not valid 
Aborted 

以下是我的代码。

int c; 
std::string config = def+std::string("SamplesConfig.xml"); 
std::string cal = def+std::string("calibration.bin"); 
while ((c = getopt(argc, argv, "a:c"))>=0) 
{ 
    switch(c) 
    { 
     case 'a': 
     { 
      config = std::string(optarg); 
      printf("%s", (char *)config.c_str()); 
      break; 
     } 
     case 'c': 
     { 
      cal = std::string(optarg); 
      printf("%s", (char *)cal.c_str()); 
      break; 
     } 
     default: 
     { 
      break; 
     } 
    } 
} 
+0

你能减少这一切吗?你知道哪一行代码实际上是在抛出错误吗?你有调试过吗? – SirPentor 2012-07-13 16:38:25

回答

0

你不应该调用getopt(“a:b:c:”)吗?我想像你刚才指定的那样,当它达到那个点时,optarg将是空的。

+0

谢谢。这是我第一次使用命令行参数,所以我没有意识到我需要以冒号结尾。 – user1469474 2012-07-13 16:50:39

+1

好吧,你不需要,但省略它意味着它将'c'视为不带任何参数的选项。 a:c:表示-a接受一个参数,-c接受一个参数,而a:c表示-a接受一个参数,但-c不接受 – 2012-07-13 16:58:17