【问题标题】:C Command-Line ArgumentsC 命令行参数
【发布时间】:2013-09-23 14:52:11
【问题描述】:

我理解指针(我认为),并且我知道 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')。我只是有点失落。

【问题讨论】:

  • 可能不是字符串,而是字符。 strcmp 比较字符串。您可以使用 'A' == 'A' 比较字符。
  • 据我所知,args[4] 的值是一个字符串。因此,取该字符串的 index 0 的值(即 args[4][0]`)应该可以工作,因为比较值都是两个字符,但情况似乎并非如此。
  • 显然我做的比较正确,但语句的逻辑是错误的。典型的我,但感谢您查看我的问题:)

标签: c pointers character command-line-arguments


【解决方案1】:

你的代码

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')

【讨论】:

  • 该死的......我需要在布尔逻辑上重新学习该课程。我习惯了使用|| 来表示数值表达式,忘记了字符比较的目的。非常感谢!