作为初学者,我一直在尝试该库的一些功能 string.h
并且有一些关于该功能的问题 strcmp
.
我编写了比较两个字符串的程序。如果它们相等,则返回 YES
和NO
否则。
#include <stdio.h>
#include <string.h>
int main() {
char a[100];
char b[15] = "hello";
fgets(a, 100, stdin);
int compare;
compare = strcmp(a, b);
if(compare == 0) {
printf("YES");
}
else {
printf("NO");
}
return 0;
}
运行后,即使我从键盘输入 hello
我得到一个NO
。当我添加行 printf("%d", compare)
时事实证明,对于任何输入我都会得到 1
,即 a
中的停止字符大于b
中的那个.
我的错误在哪里?
最佳答案
fgets
如果源数组中有足够的空间,则会附加与 Enter 键对应的新行字符。
在按以下方式将字符串与另一个字符串进行比较之前,您应该删除该字符
a[strcspn( a, "\n" )] = '\0';
例如
#include <stdio.h>
#include <string.h>
int main() {
char a[100];
char b[15] = "hello";
fgets(a, 100, stdin);
a[strcspn( a, "\n" )] = '\0';
int compare;
compare = strcmp(a, b);
if(compare == 0) {
printf("YES");
}
else {
printf("NO");
}
return 0;
}
关于C:使用 strcmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766185/