2013-09-23 113 views
0

我理解指针(我认为),并且我知道C中的数组作为指针传递。我假设这适用于main()命令行参数为好,但对我的生活,当我运行下面的代码,我不能做的命令行参数的简单比较:与C命令行参数

#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')。我只是有点失落。

+0

也许这不是一个字符串,而是一个字符。 Strcmp比较字符串。您可以使用'A'=='A'来比较字符。 – Reinherd

+0

据我所知,'args [4]'的值是一个字符串。因此,取该字符串的'index 0'值(即args [4] [0]')应该有效,因为比较值都是字符,但似乎并非如此。 –

+0

显然我正确地进行了比较,但是声明的逻辑错误。典型的我,但感谢看看我的问题:) –

回答

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

该死的......我需要重新在布尔逻辑上的类。我习惯于使用'||'来表示数字表达式,而我忘记了字符比较的目的。谢谢一堆! –