You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中strcmp函数返回错误比较结果的问题求助

C语言strcmp字符串比较错误问题

源代码

#include<stdio.h>
#include<string.h>

int main() {
unsigned char pass[100]="Try to hack me";
unsigned char input[100];

printf("Enter the secret string: ");
scanf("%s",input);

if(strcmp(pass,input))
printf("Wrong Password\nAccess Denied\n");
else
printf("Right password\nAccess Granted!!\n");

return 0;
}

问题场景

运行编译后的程序时,输入正确密码Try to hack me,却始终返回错误提示:

professor@CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme 
Enter the secret string: Try to hack me
Wrong Password
Access Denied
professor@CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme 
Enter the secret string: Try to hack me
Wrong Password
Access Denied

问题原因

  • scanf("%s")的读取规则是:以**空白字符(空格、换行、制表符等)**作为输入终止符。当你输入Try to hack me时,scanf只会把第一个空格前的Try存入input数组,后面的to hack me会被留在输入缓冲区,不会被读取。
  • 此时strcmp(pass, input)实际比较的是完整字符串Try to hack me和截断后的Try,两者必然不相等,因此触发错误提示逻辑。

解决方案

要读取包含空格的完整字符串,改用fgets替代scanf,同时注意fgets会读取输入末尾的换行符\n,需要手动去除避免影响比较结果。修改后的代码如下:

#include<stdio.h>
#include<string.h>

int main() {
unsigned char pass[100]="Try to hack me";
unsigned char input[100];

printf("Enter the secret string: ");
// 读取整行输入(包含空格)
fgets(input, sizeof(input), stdin);
// 去掉fgets读取到的换行符
input[strcspn(input, "\n")] = '\0';

if(strcmp(pass,input))
printf("Wrong Password\nAccess Denied\n");
else
printf("Right password\nAccess Granted!!\n");

return 0;
}

strcspn(input, "\n")会返回input中第一个\n的位置,将该位置替换为字符串结束符\0,即可消除换行符对比较的影响。

内容的提问来源于stack exchange,提问作者Swapnil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:20:32