gpt4 book ai didi

c - 在 C 中使用 strcspn 和 fgets 的登录功能问题

转载 作者:行者123 更新时间:2023-11-30 15:01:04 26 4
gpt4 key购买 nike

我正在尝试将登录功能作为较大程序的一部分,这是简化版本:

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

int main() {
char username[50], password[50];
char real_Username[] = "user", real_Password[] = "pass";
int confirm_User, confirm_Pass;

printf("Username ");
fgets(username, 50, stdin);
printf("\n");
printf("Password ");
fgets(password, 50, stdin);

confirm_User = strcspn(username, real_Username);
confirm_Pass = strcspn(password, real_Password);

if (confirm_User == 0 && confirm_Pass == 0) {
printf("Correct\n");
} else {
printf("Incorrect\n");
}

getch();
}

在某些情况下,当用户没有输入正确的文本时,confirm_Userconfirm_Pass的结果仍然为0。例如,输入 userpad 仍算作正确输入。我该如何修复此代码?

最佳答案

这里有一些困惑:

  • strcspn(s1, s2) 计算 s1 开头处不存在于 s2 中的字符数,可用于从由 fgets() 填充的缓冲区中去除换行符。
  • 要比较字符串,您应该使用 strcmp()

这是更正后的版本:

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

int main(void) {
char username[50] = "", password[50] = "";
char real_Username[] = "user", real_Password[] = "pass";
int confirm_User, confirm_Pass;

printf("Username ");
fgets(username, 50, stdin);
// strip the trailing newline if any
username[strcspn(username, "\n")] = '\0';

printf("\n");
printf("Password ");
fgets(password, 50, stdin);
// strip the trailing newline if any
password[strcspn(password, "\n")] = '\0';

confirm_User = strcmp(username, real_Username);
confirm_Pass = strcmp(password, real_Password);

if (confirm_User == 0 && confirm_Pass == 0) {
printf("Correct\n");
} else {
printf("Incorrect\n");
}

getch();
}

另请注意,最好在提示用户输入密码时禁用回显,但没有可移植的方法来执行此操作。

关于c - 在 C 中使用 strcspn 和 fgets 的登录功能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com