【发布时间】: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]中的那些单个字符不是字符串,而是几个单独的字符