c++ - 带数字偏移量的命令行参数选项

标签 c++ command-line-arguments argv getopt argc

我想确保 -f 之后的选项/参数是 0-9 之间的数字。总共必须有 10 个参数,顺序不限。唯一的条件是 -f 后面必须跟一个数字。

/* Ensure that the -f option is included in the arguments
and it is preceeded by valid digit between 0 -9 */
int Crypto::offsetValidation( int argc, char *argv[] )
{
    for( int i = 0; i < argc; i++ )
    {
        if(argv[i] == string("-f"))             
        {           
            cout << "offset" << endl;           
            return offset;
        }       
    }   

    cout << "Usage: -f is required for offset" << endl;
    exit(EXIT_FAILURE);

    return 0;   
}

最佳答案

将评论转录为答案

使用getopt() ,然后检查它用 optarg 指向的是一位数 (strlen(optarg) == 1 && isdigit(optarg[0]))。临时参数解析会让您陷入各种临时问题。

How do I ensure that it is right after the " -f " option though…

您可以编写类似于以下的代码:

int opt;
while ((opt = getopt(argc, argv, "f:")) != -1)
{
    switch (opt)
    {
    case 'f':
        if (strlen(optarg) == 1 && isdigit(optarg[0]))
            f_value = optarg[0] - '0';
        else
            err_exit("Invalid value '%s' for -f option", optarg);
        break;
    default:
        …usage error and exit…;
        break;
    }
}

你不能保证你有 -f3 或其他什么,但你的原始字符串比较不允许这样做。使用 getopt(),可以保证如果您在命令行上有 -f3-f 3,那么 strcmp (optarg, "3") == 0。我很高兴地假设你只有 -f 参数;您需要更多代码来处理其他代码,无论它们是什么。您需要将额外的选项字母添加到当前包含 "f:" 的字符串中,并将额外的 case 添加到开关中,以及用于处理它们的变量。

我还应该补充一点,这是可以用 C++ 编译的 C 代码,而不是“真正的 C++”。有一个 Boost在 C++ 中解析选项的库可能是更好的选择——如果你被允许在你的项目中使用 Boost。通常还有许多其他选项解析器。 GNU getopt_long()也广泛用于长选项名称解析(--file name-of-file 等)。

关于c++ - 带数字偏移量的命令行参数选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270424/

相关文章:

c++ - 从 NFD 到 NFC 的 OSX 和 C++ unicode 转换

C++ cin.clear() 和 cin.ignore(...) 问题

c - 在 C 中解析命令行参数

java - 如何使用 Commons CLI 传递(和获取后)参数数组?

c - 使用 argv[] 时我的代码不接受命令行参数

c# - 如何在两个 AVX2 vector 之间交换 128 位部分

.NET System::String 到存储在 char* 中的 UTF8 字节

go - 如何在 Go 中获取命令参数?

c - 为什么 argv 可以使用自增运算符

command-line-arguments - 如何在 Dart 中访问 argv/命令行选项?