为什么我的命令行参数不被读取?

时间:2015-05-26 20:07:11

标签: c++ command arguments

我在我的程序中调用它:

std::string gameDirectory = "";
for (int i = 1; i < argc; i++)
    {
        if (argv[i] == "-game")
            gameDirectory = argv[i + 1];
    }

    if (gameDirectory == "")
        exit(0);

使用命令行参数

-game demo

它拒绝设置gameDirectory。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

<?php include_once( $_SERVER['DOCUMENT_ROOT'] . "/app/libraries/plivo.php"); $dst = $_REQUEST['ForwardTo']; if(! $dst) $dst = $_REQUEST['To']; $src = $_REQUEST['CLID']; if(! $src) $src = $_REQUEST['From'] or ""; $cname = $_REQUEST['CallerName'] or ""; $hangup = $_REQUEST['HangupCause']; $dial_music = $_REQUEST['DialMusic']; $disable_call = $_REQUEST['DisableCall']; $r = new Response(); if($dst) { $dial_params = array(); $record_params = array( 'action' => '*****/record-onanswer.php', 'startOnDialAnswer' => 'true', 'time_limit' => '600' ); if($src) $dial_params['callerId'] = $src; if($cname) $dial_params['callerName'] = $cname; if(substr($dst, 0,4) == "sip:") $is_sip_user = TRUE; else $is_sip_user = FALSE; if($is_sip_user and in_array($disable_call, array("all", "sip"))) { $r->addHangup(array("reason" => "busy")); } elseif (! $is_sip_user and in_array($disable_call, array("all", "number"))) { $r->addHangup(array("reason" => "busy")); } else { if($dial_music) { $dial_params["dialMusic"] = $dial_music; $d = $r->addDial($dial_params); $r->addRecord($record_params); } else $d = $r->addDial($dial_params); $r->addRecord($record_params); if($is_sip_user) $d->addUser($dst); else $d->addNumber($dst); } } else { $r->addHangup(); $r->stop_record($params); } header("Content-Type: text/xml"); echo($r->toXML()); ?> 的类型为argv[i],指针的直接比较只有在它们指向同一位置时才会返回true。程序参数永远不会指向与现有常量字符串相同的位置,因此永远不会访问const char*

您需要将任一字符串设为if(具有==重载以与char指针进行比较),或者使用std::string来比较参数。

strcmp

答案 1 :(得分:0)

打开编译警告!!!

main.cpp: In function 'int main(int, char**)':
main.cpp:8:24: warning: comparison with string literal results in unspecified behaviour [-Waddress]
         if (argv[i] == "-game")
                        ^

此警告会告诉您需要知道的所有事项(live)。

使用strcmp比较C字符串。