C Command-Line Arguments

2019-08-26 01:45发布

问题:

I understand pointers (I think), and I know that arrays in C are passed as pointers. I'm assuming this applies to command-line arguments in main() as well, but for the life of me I can't do simple comparisons on command-line arguments when I run the following code:

#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;
}

with the following arguments: othello 8 0 B

All of the comparisons work except for the last - checking for a character match. I tried using strcmp() as I did in the second comparison suing "B", "b" (etc) as arguments, but that didn't work. I also tried casting args[4][0] to a char and that also did not work. I tried dereferencing args[4], and I tried casting that value as well.

Output:

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'

I really don't understand what's going on. Last time I wrote something in C was a year ago, but I remember having a lot of trouble manipulating characters and I have no idea why. What is the obvious thing I'm missing?

The question: How do I compare the value at args[4] to a character (i.e. args[4] != 'B' _or_ args[4][0] != 'B'). I'm just a little bit lost.

回答1:

Your code

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

will always evaluate to TRUE -- it should be

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