C语言字符串比较:使用strcmp()函数代替==运算符
这段代码存在一些问题。在C语言中,我们不能直接使用'=='运算符来比较两个字符串是否相等。正确的比较字符串的方式是使用'strcmp()'函数来比较两个字符串。
下面是修改后的代码:
#include <stdio.h>
#include <string.h>
int main()
{
int ret, ch;
char password[20] = { 0 };
printf("请输入密码: ");
scanf("%s", password);
if (strcmp(password, '123456') == 0)
{
printf("密码正确\n");
}
else
{
printf("密码错误\n");
}
while ((ch = getchar()) != '\n')
{
;
}
printf("请输入确认与否Y/N: ");
ret = getchar();
getchar(); // 消耗换行符
if (ret == 'Y' || ret == 'y')
{
printf("确认成功\n");
}
else
{
printf("取消\n");
}
return 0;
}
这样修改后,代码将能正确比较密码并进行相应的操作。同时,获取确认与否时也可以输入小写字母'y',而不仅限于大写字母'Y'。
原文地址: https://www.cveoy.top/t/topic/hIx 著作权归作者所有。请勿转载和采集!