繁体   English   中英

C命令行参数

[英]C Command-Line Arguments

我理解指针(我认为),并且我知道C中的数组作为指针传递。 我假设这也适用于main()命令行参数,但是为了我的生命,当我运行以下代码时,我无法对命令行参数进行简单的比较:

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

int main(int numArgs, const char *args[]) {

    for (int i = 0; i < numArgs; i++) {
        printf("args[%d] = %s\n", i, args[i]);
    }

    if (numArgs != 5) {
        printf("Invalid number of arguments. Use the following command form:\n");
        printf("othello board_size start_player disc_color\n");
        printf("Where:\nboard_size is between 6 and 10 (inclusive)\nstart_player is 1 or 2\ndisc_color is 'B' (b) or 'W' (w)");
        return EXIT_FAILURE;
    }
    else if (strcmp(args[1], "othello") != 0) {
        printf("Please start the command using the keyword 'othello'");
        return EXIT_FAILURE;
    }
    else if (atoi(args[2]) < 6 || atoi(args[2]) > 10) {
        printf("board_size must be between 6 and 10");
        return EXIT_FAILURE;
    }
    else if (atoi(args[3]) < 1 || atoi(args[3]) > 2) {
        printf("start_player must be 1 or 2");
        return EXIT_FAILURE;
    }
    else if (args[4][0] != 'B' || args[4][0] != 'b' || args[4][0] != 'W' || args[4][0] != 'w') {
        printf("disc_color must be 'B', 'b', 'W', or 'w'");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

具有以下参数: othello 8 0 B

除最后一个比较外,所有比较均有效-检查字符是否匹配。 我尝试使用strcmp() ,就像在第二次比较中一样,使用“ B”,“ b”(等)作为参数,但这没有用。 我还尝试将args[4][0]强制转换为char ,但这也不起作用。 我尝试取消引用args[4] ,也尝试转换该值。

输出

args[0] = C:\Users\Chris\workspace\Othello\Release\Othello.exe
args[1] = othello
args[2] = 8
args[3] = 1
args[4] = B
disc_color must be 'B', 'b', 'W', or 'w'

我真的不明白发生了什么。 我上一次用C语言写东西是在一年前,但我记得在操作字符时遇到很多麻烦,我也不知道为什么。 我想念的最明显的东西是什么?

问题 :如何将args[4]处的值与字符进行比较(即args [4]!=' B'_ _ args [4] [0]!='B')。 我只是有点迷路。

您的密码

else if (args[4][0] != 'B' || args[4][0] != 'b' || args[4][0] != 'W' || args[4][0] != 'w')

始终会评估为TRUE应该是

else if (args[4][0] != 'B' && args[4][0] != 'b' && args[4][0] != 'W' && args[4][0] != 'w')

暂无
暂无

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

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