I have been looking all over for how to compare char elements in a char array correctly, but it is not working out for me. I am trying to compare the first char in a char array to an operator (checking to see if a + or -) exists.
EDIT: Saw my mistake. Logic error in the if statement. Thank you all for such quick responses.
At first I tried this:
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
Then I read some more posts and saw that I should be comparing the chars using strcompare, so then I tried this: if( !strcmp(input[0],'+') || !strcmp(input[0],'-') )
However, they still don’t seem to be comparing properly. I get a segmentation fault with the above code and with my previous code, it would print the operator, but still go into the if statement saying that the format was incorrect. I am still fairly new to C, so any advice or tips on how I can get these chars to compare correctly will be much appreciated. Thanks.
The logic in the original
ifcondition is incorrect:That will always be true: if
'+'== input[0]the condition equates tofalse || true, and vice versa for'-' == input[0].It should be: