我一直在寻找如何正确比较 char 数组中的 char 元素,但它对我不起作用。我正在尝试将 char 数组中的第一个字符与运算符进行比较(检查是否存在 + 或 -)。
编辑:看到我的错误。 if 语句中的逻辑错误。感谢大家如此迅速的回复。
起初我试过这个:
main(int argc, char *argv[]){
int i;
int len;
char input[10];
for(i = 1; i < 8; i++){
len = strlen(argv[i]);
strcpy(input,argv[i]);
//debug purposes
printf("%c\n",input[0]);
if(input[0] != '+' || input[0] != '-') {
printf("incorrect number format. %s has no sign.\nnow terminating.\n", input);
}// end if
}//end for
}//end main
然后我阅读了更多帖子,发现我应该使用 strcompare 比较字符,所以我尝试了这个:if( !strcmp(input[0],'+') || !strcmp(input [0],'-') )
然而,他们似乎仍然没有正确地进行比较。我在上面的代码和我以前的代码中遇到了段错误,它会打印运算符,但仍然进入 if 语句,说格式不正确。我对 C 还是很陌生,所以任何关于如何让这些字符正确比较的建议或技巧将不胜感激。谢谢。
最佳答案
原if
条件中的逻辑不正确:
if(input[0] != '+' || input[0] != '-')
这将永远为真:如果 '+'== input[0]
条件等于 false || true
,对于 '-' == input[0]
反之亦然。
应该是:
if(input[0] != '+' && input[0] != '-')
关于将数组中的 char 元素与运算符进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9168550/