C命令行参数 [英] C Command-Line Arguments
问题描述
我理解指针(我认为),并且我知道C中的数组作为指针传递。我假设这也适用于 main()
中的命令行参数,但是对于我来说,我无法在以下情况下对命令行参数进行简单比较我运行以下代码:
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;
}
具有以下参数: othello 8 0 B
除最后一个比较外,所有比较均有效-检查字符是否匹配。我尝试在第二次比较中使用 strcmp()
作为参数,但以 B, b(等)为参数,但这没有用。我还尝试将 args [4] [0]
强制转换为 char
,但这也没有用。我尝试取消引用 args [4]
,也尝试转换该值。
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.
输出:
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语言写东西是在一年前,但是我记得在操作字符时遇到很多麻烦,我也不知道为什么。我最想念的东西是什么?
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?
问题:如何比较 args的值[ 4]
转换为字符(即args [4]!='B' _ 或 _ args [4] ] [0]!='B')。我只是迷路了。
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.
推荐答案
您的代码
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')
这篇关于C命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!