【问题标题】:How to handle command line arguments in C++ that has negative sign (-) in linux terminal?如何在 Linux 终端中处理带有负号 (-) 的 C++ 命令行参数?
【发布时间】:2019-04-04 04:02:29
【问题描述】:

我需要这个来完成一项任务。我知道标准命令行输入在 C++ 中是如何工作的。如果我有一个名为 training 的可执行文件,那么我可以在终端中编写以下行:

./training input.text output1 output2

在这种情况下,我的主要方法如下:

int main( int argc, char* argv[] ){
     take_input( argv[1] );
     make_output( argv[2], argv[3] );
}

我的函数声明如下:

int take_input( string filename );
int make_output( string filename, string filename2 )

但是,我需要将命令行编写如下:

training -i input.csv -os output1 -oh output2

我不知道如何进行修改。非常感谢您的帮助。

【问题讨论】:

标签: c++ linux parsing command-line command-line-arguments


【解决方案1】:

getopt() 可以工作,但是如果您的需求很小并且您不想添加外部依赖项,您可以编写自己的小辅助函数来查找破折号关键字在 argv 数组中的位置,像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Returns the index of the specified keyword (e.g. "-oh")
// or returns -1 if the keyword doesn't exist
static int find_keyword(int argc, char *argv[], const char * keyword)
{
   for (int i=0; i<argc; i++)
   {
      if (strcmp(argv[i], keyword) == 0) return i;
   }
   return -1;
}

int main( int argc, char* argv[] )
{
   const int iIndex = find_keyword(argc, argv, "-i");
   if (iIndex < 0) {printf("No -i keyword found!  Exiting!\n"); exit(10);}

   const int osIndex = find_keyword(argc, argv, "-os");
   if (osIndex < 0) {printf("No -os keyword found!  Exiting!\n"); exit(10);}

   const int ohIndex = find_keyword(argc, argv, "-oh");
   if (ohIndex < 0) {printf("No -oh keyword found!  Exiting!\n"); exit(10);}

   take_input( argv[iIndex+1] );
   make_output( argv[osIndex+1], argv[ohIndex+1] );
}

请注意,所示程序不会检查破折号参数之后的下一个参数是否存在;例如如果您运行“./a.out -i foo -os bar -oh”,则 make_output 的第二个参数将作为 NULL 传入。您可以修改 find_keyword() 以检查这种可能性并在这种情况下返回 -1,如果您想在错误处理中更加稳健。

【讨论】:

  • 非常感谢 Jeremy,这很有帮助。
【解决方案2】:

在 Linux 上,您只需包含 unistd.h 并使用 getopt

【讨论】:

  • 如果有人可以提供修改,那会很有帮助,不过我正在学习 get opt。
猜你喜欢
  • 2021-01-27
  • 2014-07-03
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2017-08-31
  • 1970-01-01
相关资源
最近更新 更多