如何解决如何使用哈希表保存用户登录/注册的数据?
我正在尝试使用客户端和服务器为 C 语言的游戏制作登录/注册功能。用户应该能够注册、登录,哈希表将能够知道使用了什么用户名或密码是否不正确。我认为我的代码有效,但是当程序结束时,哈希表再次重置,这使得它毫无意义。有没有办法保存用户名和密码,这样它就不会使用我已经制作的代码重置?
#include <stdio.h>
#include <string.h>
// hash function
int hashFunction(const char* username){
int result = 0;
for(int i = 0; i < strlen(username); i++){
result = (13*result + username[i]) % 3119;
}
return result;
}
void login_register(int mode,char* username,char* password,char hashTable[][21]){
if(mode == 1) { // register mode will be 1
char new_username[21];
while(1){
printf("Enter a username.\n");
scanf("%s",new_username);
// check for duplicate here
int hashResult = hashFunction(new_username);
if(strcmp(hashTable[hashResult%128],".") == 0){
strcpy(username,new_username);
break;
}
else {
printf("Username is taken try again.\n");
}
}
char new_password[21];
printf("Enter a password.\n");
scanf("%s",new_password);
// copy over the newly input values into the parameters
strcpy(password,new_password);
}
else{
char new_username[21];
char new_password[21];
printf("Enter your username.\n");
scanf("%s",new_username);
strcpy(username,new_username);
while(1){
printf("Enter your password.\n");
scanf("%s",new_password);
strcpy(password,new_password);
// check for duplicate here
int hashResult = hashFunction(new_username);
if(strcmp(hashTable[hashResult%128],password ) == 0){
break;
}
else {
printf("Password is incorrect try again.\n");
}
}
}
}
int main()
{
char hashTable[128][21];
// 128 total strings in the array
//each string will be 20 chars long plus the '\0' at the end of each string
for(int i = 0; i < 128; i++){
strcpy(hashTable[i],"."); // we initialize each index of the hash table to just have a default value so we have something to compare against
}
int mode = 1;
char username[21]; // variable to hold the username
char password[21]; // variable to hold the password
//strcpy(hashTable[35],"password"); // this was just me testing ignore that
login_register(mode,username,password,hashTable);
printf("%s\n",username);
printf("%s\n",password);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。