【问题标题】:How to compare 2 characters with strcmp in c?如何在c中将2个字符与strcmp进行比较?
【发布时间】:2021-04-02 21:20:27
【问题描述】:

我正在尝试将 2 个字符与使用 strcmp 进行比较。我给出了陈述,但是当我输入 a 和 a 作为两个字符时,它给出了 -1。我不明白为什么?这是我的代码:

#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20

int main()
{
    //comparing to characters
    char c1[1], c2[1];
    int result;
    //asking user to enter characters respectively
    printf("6.Enter the first character you want to compare: \n");
    scanf("%s", c1);
    getchar();
    printf("7.Enter the second character you want to compare: \n");
    scanf("%s", c2);
    getchar();
    //comparing c1 with c2 using strcmp
    //result = strcmp(c1, c2);
    if (strcmp(c1, c2) == 0)
    {
        printf("0\n");
    }
    else if (c1 < c2)
    {
        printf("-1\n");
    }
    else
    {
        printf("1\n");
    }
}

【问题讨论】:

  • char[1] 是一个零长度 C 字符串。记住 NUL 终止符!
  • 避免悲伤,不要使用scanf("%s", ....研究fgets()
  • 关于; if (strcmp(c1, c2) == 0) 函数:strcmp() 比较 NUl 终止的字符串,但 c1[1]c2[1] 中的那些单个字符不是字符串,而是几个单独的字符

标签: c strcmp


【解决方案1】:

你有一个缓冲区溢出。 Don't use scanf.

即使您的输入只是一个char,您仍然需要c1c2 中的另一个用于终止:'\0'

    char c1[2], c2[2];

此外,您正在比较内存地址,因为 c1c2char 数组。比较 chars 代替:c1[0] &lt; c2[0]

    if (strcmp(c1, c2) == 0)
  {
    printf("0\n");
  }
    else if (c1[0] < c2[0])
  {
    printf("-1\n");
  }
    else
  {
    printf("1\n");
  }

【讨论】:

  • 这并没有解决缓冲区对于存储 C 字符串完全无用的问题。它们还不够大。
  • 学究式地,strcmp() 比较就像字符是 unsigned char 而不是 char 所以 c1[0] &lt; c2[0] 需要做一些工作。
【解决方案2】:

发生这种情况是因为: 你在做一个scanf之后做getchar!第二个输入将被 getchar 接收,c2 将被分配一些垃圾值。

另外:你应该比较字符:所以 c1[0]

【讨论】:

    【解决方案3】:

    我对@mkayaalp 的回答做了一些小改进,我的代码运行正常。这里:

        if (c1[0] == c2[0])
      {
        printf("0\n");
      }
        else if (c1[0] < c2[0])
      {
        printf("-1\n");
      }
        else
      {
        printf("1\n");
      }
    

    我还更改了 if 部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2011-06-26
      • 1970-01-01
      • 2017-12-13
      • 2017-10-02
      相关资源
      最近更新 更多