[英]strcmp giving non-zero output even if strings match
In the program below, I tried to compare the string in the i-th place in the string using strcmp
.在下面的程序中,我尝试使用
strcmp
比较字符串中第 i 个位置的字符串。 The test case I used is 1+2+2+1+3
.我使用的测试用例是
1+2+2+1+3
。 However, except the first iteration of the loop, strcmp
shows non-zero output even when the strings match.但是,除了循环的第一次迭代外,即使字符串匹配,
strcmp
也会显示非零 output。 Why is this happening?为什么会这样?
#include <stdio.h>
#include <string.h>
int main() {
char num[101];
int n1 = 0, n2 = 0, n3 = 0;
scanf(" %s", num);
int len = strlen(num);
for (int i = 0; i < len; i = i + 2) {
char dig = num[i];
printf("\ndig: %c", dig);
int c1 = strcmp(&dig, "1");
printf("\nc1: %d", c1);
if (c1 == 0) {
n1++;
continue;
}
int c2 = strcmp(&dig, "2");
printf("\nc2: %d", c2);
if (c2 == 0) {
n2++;
continue;
}
int c3 = strcmp(&dig, "3");
printf("\nc3: %d\n\n", c3);
if (c3 == 0) {
n3++;
continue;
}
}
printf("\nn1: %d n2: %d n3: %d", n1, n2, n3);
for (int j = 0; j < len; j = j + 2) {
if (n1 > 0) {
num[j] = '1';
n1--;
continue;
}
if (n2 > 0) {
num[j] = '2';
n2--;
continue;
}
if (n3 > 0) {
num[j] = '3';
n3--;
continue;
}
}
printf("\n%s", num);
return 0;
}
The strcmp
expects both arguments to be null-terminated strings . strcmp
期望 arguments 都是以空字符结尾的字符串。
The expression &dig
is a pointer to a single character, it's not a null-terminated string.表达式
&dig
是指向单个字符的指针,它不是以空字符结尾的字符串。 That means strcmp
will go out of bounds to find the terminator, and you will have undefined behavior .这意味着
strcmp
将 go 越界找到终止符,并且您将有未定义的行为。
If you want to compare two characters, you can do it with the ==
operator:如果要比较两个字符,可以使用
==
运算符:
if (dig == '3')
{
...
}
You can also use a switch
statement:您还可以使用
switch
语句:
switch (dig)
{
case '1':
// Do something...
break;
case '2':
// Do something...
break;
case '3':
// Do something...
break;
default:
// No match...
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.