c - 为什么看起来字符串不相等?
问题描述
int main()
{
int n = 100;
char a[n];
char b[ ]="house";
fgets(a,n-1,stdin); // type "house"
if (strcmp(a,b) == 0)
printf("The strings are equal.\n");
else
printf("The strings are not equal.\n");
return 0;
}
解决方案
Reason why this
if (strcmp(a,b) == 0) { }
is not true because fgets()
stores the \n
at the end of buffer. So here array a
looks like house
and array b
looks like house\n
(If ENTER
key was pressed after entering input char's) and strcmp(a,b)
doesn't return 0
.
From the manual page of fgets()
fgets()
reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
One way is to use strcspn()
which removes the trailing \n
. For e.g
fgets(a,n,stdin);
a[strcspn(a, "\n")] = 0;
Now compare the char array like
if (strcmp(a,b) == 0) {
printf("The strings are equal.\n");
}
else {
printf("The strings are not equal.\n");
}
推荐阅读
- r - 绘制一个类别变量的一个类别相对于第二个变量的所有类别的份额
- java - 在 Java 中选择打印机以打印 JasperReport
- excel - 如何自动更新 Excel 中使用特定 VBA 代码的单元格?
- html - 有没有办法在同一元素悬停时激活“之后”伪元素?
- angular - 为什么 Angular CLI 9.01 无法创建 bazel 项目?
- python - 使用 django 按类别(多对多字段)过滤内容
- python - 在 Ubuntu 18.04 上安装最新版本的 QGis
- python - Python 字符串 2d 列表到混合整数/字符串列表
- javascript - 在 Gulp 中处理数组以在每个目录中创建包含有序文件的包
- r - 为什么 ggplot 不能正确循环数据帧?