【问题标题】:Handling Arguments in C++ not working处理 C++ 中的参数不起作用
【发布时间】:2016-02-04 11:21:30
【问题描述】:

我正在使用此代码:

    int handleArgs(int argc, char *argv[]) {

    if(argc <= 1)
      {return 0;} 
    else 
      { // If no arguments, terminate, otherwise: handle args

        for(int i=1; i<argc; i++) {

          if (argv[i] == "-a" || argv[i] == "--admin") 
            {           // If admin argument
              char *pwd = argv[i+1];            // i + 1 b/c we want the next argument; the password

                if(pwd == "1729" || pwd == "GabeN") 
                 {                  // Verify Password

                cout << "Sorry, console feature unavailable.\n" << endl;// Will replace with console function when I get to it

                } 
               else 
                {
                  cout << "Wrong/No passkey, bruh.\n" << endl;
                }       // If the password is wrong


           } 
          else if (argv[i] == "-v" || argv[i] == "--version") 
           {        // If user asks for version info

            cout << "You are running\nDev0.0.0" << endl;            // Tell the user the version


           }  
             else if (argv[i]==" -h" || argv[i]=="--help") 
              {

                cout << "Usage: " << argv[0] << " -[switch] argument(s)\n";
                cout << "   -a,  --admin        Open console view. Requires password\n";
                cout << "   -v,  --version      Print version and exit\n";
                cout << "   -h,  --help         Print this message and exit\n" << endl;

                } 
               else {
                 cout << "Is you dumb?\n    '" << argv[0] << " --help' for help" << endl;       // Insult the user
                    }                       
        }
    }
  return 1;
  }

但是,每次我给它一个参数时,我都会收到无效的参数消息(最后一个 else 语句):

Is you dumb?
    'main --help' for help

我是 C++ 新手,我不知道自己在做什么(错误)。谁能给我一些有用的见解?谢谢

--破碎代码

【问题讨论】:

  • 你能告诉我你是如何传递参数的......仅供参考......
  • @MGP int main(int argc, char *argv[])
  • @MGP handleArgs(argc, argv);
  • 我的意思是你是怎么打电话的......只是为了例如。文件名 arg1 arg2....有些像这样...对吗?
  • argv[i] == "-a" 等不会像您认为的那样做。您需要改用strcmp

标签: c++ command-line arguments


【解决方案1】:

argv 是一个 C 字符串数组 (char*)。您正在使用 == 并比较内存地址,而不是 C++ 字符串提供的重载 == 运算符。您应该使用strncmp 来比较您的字符串(它比strcmp 更安全)。虽然在这里并不重要,因为您正在与文字进行比较,这可以保证其中一个会结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2019-09-15
    • 2015-10-06
    • 2012-03-21
    • 1970-01-01
    相关资源
    最近更新 更多