即使字符串匹配,strcmp也提供非零输出
在下面的程序中,我尝试使用即使字符串匹配,strcmp也提供非零输出,c,string,strcmp,C,String,Strcmp,在下面的程序中,我尝试使用strcmp比较字符串中第I位的字符串。我使用的测试用例是1+2+2+1+3。但是,除了循环的第一次迭代之外,strcmp即使在字符串匹配时也显示非零输出。为什么会这样 #include <stdio.h> #include <string.h> int main() { char num[101]; int n1 = 0, n2 = 0, n3 = 0; scanf(" %s", num); int len
strcmp
比较字符串中第I位的字符串。我使用的测试用例是1+2+2+1+3
。但是,除了循环的第一次迭代之外,strcmp
即使在字符串匹配时也显示非零输出。为什么会这样
#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;
}
#包括
#包括
int main(){
字符数[101];
int n1=0,n2=0,n3=0;
scanf(“%s”,num);
int len=strlen(num);
对于(int i=0;i0){
num[j]=“1”;
n1-;
持续
}
如果(n2>0){
num[j]=“2”;
n2-;
持续
}
如果(n3>0){
num[j]=“3”;
n3--;
持续
}
}
printf(“\n%s”,num);
返回0;
}
要求两个参数都以null结尾字符串
表达式&dig
是指向单个字符的指针,它不是以null结尾的字符串。这意味着strcmp将越界找到终止符,并且您将有未定义的行为
如果要比较两个字符,可以使用==
运算符:
if (dig == '3')
{
...
}
您还可以使用开关语句:
switch (dig)
{
case '1':
// Do something...
break;
case '2':
// Do something...
break;
case '3':
// Do something...
break;
default:
// No match...
break;
}
&dig
指向单个字符而不是字符串<代码>strcmp
需要字符串。C中的字符串是以NUL结尾的字符序列。使用非字符串调用strcmp是未定义的行为。在一个不相关的注释中,scanf
的%s
格式将自动跳过前导空格,不需要使用格式为%s
的前导空格。