【问题标题】:strcmp giving non-zero output even if strings match即使字符串匹配,strcmp 也会给出非零输出
【发布时间】:2020-09-27 01:58:10
【问题描述】:

在下面的程序中,我尝试使用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;
}

【问题讨论】:

  • &amp;dig 指向单个字符而不是字符串。 strcmp 需要一个字符串。 C 中的字符串是 NUL 终止 字符序列。使用非字符串调用 strcmp 是未定义行为。
  • 在不相关的注释中,scanf%s 格式将自动跳过前导空格,不需要您在格式 " %s" 中的前导空格。

标签: c string strcmp


【解决方案1】:

strcmp 期望两个参数都是 null 终止 字符串。

表达式&amp;dig 是一个指向单个字符的指针,它不是一个以空字符结尾的字符串。这意味着strcmp 将越界寻找终止符,您将有未定义的行为

如果要比较两个字符,可以使用== 运算符:

if (dig == '3')
{
    ...
}

您也可以使用switch 声明:

switch (dig)
{
case '1':
    // Do something...
    break;
case '2':
    // Do something...
    break;
case '3':
    // Do something...
    break;

default:
    // No match...
    break;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多