if
您的打印声明与您帖子的第一句话或您的表达不匹配。如果你想测试两者是否相等,你应该使用&&
而不是||
. 如果您想测试任何一个字符串是否与您的测试字符串匹配,那么您的程序就可以了。您的代码的不同部分一定有问题。这是一个示例程序来为您证明:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char *string1 = argv[1];
char *string2 = argv[2];
if ((strcmp(string1, "test1") == 0) || (strcmp (string2, "test2") ==0))
printf ("At least one string matched\n");
return 0;
}
并输出:
$ ./example test1 bad
At least one string matched
$ ./example bad test2
At least one string matched
$ ./example bad bad
$ ./example test1 test2
At least one string matched
编辑:我在进一步阅读时突然想到,您实际上可能想要测试其中一个是否完全匹配。在这种情况下,您需要在if
. 也许是这样的:
int string1Matches = (strcmp(string1, "test1") == 0);
int string2Matches = (strcmp(string2, "test2") == 0);
if ((string1Matches && !string2Matches) || (!string1Matches && string2Matches))
printf("Exactly one string matches (not both!)\n");
再次编辑:
您的新程序似乎运行良好 - 您的问题是什么?示例输出:
$ ./example
Enter the first string: test1
Enter the second string: bad
Both strings are same
$ ./example
Enter the first string: bad
Enter the second string: test2
Both strings are same
$ ./example
Enter the first string: test1
Enter the second string: test2
Both strings are same
$ ./example
Enter the first string: bad
Enter the second string: bad
You didnt enter any matching