简体   繁体   English

如何在 C++ 中解析命令行 arguments?

[英]How to parse command-line arguments in C++?

How to effectively parse this command line in C++?如何在 C++ 中有效地解析这个命令行?

program -parameter1=value1 -parameter2=value2 -parameter3=value3

How to effectively drop a combination of the parameter and value如何有效地丢弃参数和值的组合

-parameter=value

I am trying to use this code but it does not work properly:我正在尝试使用此代码,但它无法正常工作:

parameter[256], value[256],
while ( --argc > 0 )
{
   if ( *argv[argc] == '-' )
   {
       for ( char * text = argv[argc]; ; )
       {    
            switch ( * ( ++ text ) )
            {
                case '=' :
                {
                   *value = *(  text );
                    break;
                }

                default:
                {
                   *parameter = *text;
                }
            }
         }

       //Testing parameters and values
    }
}

Thanks for your comments and improvements.感谢您的评论和改进。

Did you consider boost::program_options or if you can't use boost, getopt_long ?您是否考虑boost::program_options或者如果您不能使用 boost, getopt_long

I've leveraged TCLAP ( Templatized C++ Command Line Parser Library ) in many C++ based command line apps and been very happy with it, but it might not give you all the flexibility to read the parameters in the format you are looking at, but still worth a look, boost::program_options is a good suggestion also.我已经在许多基于 C++ 的命令行应用程序中利用了 TCLAP(模板化 C++ 命令行解析器库)并且对它非常满意,但它可能无法让您灵活地以您正在查看的格式读取参数,但仍然值得一看, boost::program_options也是一个很好的建议。

You can do this a lot more transparently with std::string and functions like find_first_of , splitting off the different parts and have the nice bonus that each time a find function returns std::string::npos , you know you've got an invalid argument.您可以使用std::stringfind_first_of之类的函数更透明地执行此操作,拆分不同的部分并获得很好的奖励,即每次 find function 返回std::string::npos时,您知道您有一个无效的论点。

I'd advise you to use the standard C library for argument parsing: there is a premade function called getopt for that.我建议您使用标准 C 库进行参数解析:有一个预制的 function 称为 getopt。

*value = *( text ); This line only writes one character.这一行只写一个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM