我想做一个本地的用户注册登录的小程序,通过链表结构和文件操作实现。
以下是代码:
```#include
#include
#include
#include
#include
#define USERINFO "userinfo.txt"
#define bool int
#define true 1
#define false 0
typedef struct{
char username[10];
char code[20];
}User;
typedef struct node{
User date;
struct node *next;
}Userlist;
int read_line(char str[], int n){
int ch, i = 0;
while (isspace(ch = getchar()))
;
while (ch != '\n' && ch != EOF) {
if (i < n)
str[i++] = ch;
ch = getchar();
}
str[i] = '\0';
return i;
}
User readuser(){
char username1[10];
char code1[20];
char code2[20];
User user;
printf("请输入用户名:\n");
read_line(username1,10);
printf("请输入密码:\n");
read_line(code1,20);
for(;;){
printf("请再次输入密码:\n");
read_line(code2,20);
if(strcmp(code1,code2)==0){
strcpy(user.username,username1);
strcpy(user.code,code1);
return user;
}
else{
printf("与第一次输入的密码不同,请再次输入!\n");
}
}
}
bool insert_item(Userlist *L, User user){
Userlist* temp;
Userlist *pre = L, *p = L->next;
for (; p != NULL; pre = p, p = p->next)
;
temp = (Userlist*)malloc(sizeof(Userlist));
temp->date = user;
pre->next = temp;
temp->next = NULL;
return true;
}
void init_list(Userlist** L){
FILE* fp;
User user;
Userlist *p, *r;
(*L) = (Userlist*)malloc(sizeof(Userlist));
r = (*L);
if ((fp = fopen(USERINFO, "r")) == NULL) {
fclose(fp);
} else {
fp = fopen(USERINFO, "r");
fscanf(fp, "%s%s\n",user.username,user.code);
p = (Userlist*)malloc(sizeof(Userlist));
p->date = user;
r->next = p;
r = p;
}
while (!feof(fp)) {
fscanf(fp, "%s%s\n", user.username,user.code);
p = (Userlist*)malloc(sizeof(Userlist));
p->date = user;
r->next = p;
r = p;
}
fclose(fp);
r->next = NULL;
system("pause");
}
int save_to_file(Userlist* L){
FILE* fp;
Userlist* p;
fp = fopen(USERINFO, "r+");
if (fp == NULL) {
return false;
}
for (p = L->next; p != NULL; p = p->next) {
fprintf(fp, "%s", p->date.username);
fprintf(fp, "\t%s", p->date.code);
}
printf("存盘成功\n");
fclose(fp);
return true;
}
Userlist* search_item(Userlist* L, char name[]){
Userlist *cur, *perv;
for (cur = L, perv = NULL;
cur != NULL && strcmp(cur->date.username, name) != 0;
perv = cur, cur = cur->next)
;
if (cur == NULL) {
printf("用户名不存在/n");
return NULL;
} else if (perv == NULL) {
L = L->next;
return NULL;
} else
return cur;
}
int main(){
User userinfo;
Userlist *userlist;
int a;
char username[10];
char code[20];
init_list(&userlist);
printf("登录请按1,注册请按2.\n");
scanf("%d",a);
switch(a){
case 1:{
printf("请输入用户名:\n");
for(;;){
read_line(username,10);
if(search_item(userlist,username)==NULL){
printf("请重新输入用户名\n");
}
else{
break;
}
}
printf("请输入密码:\n");
for(;;){
read_line(code,20);
if(strcmp(search_item(userlist,username)->date.code,code)==0){
printf("登陆成功!\n");
break;
}
else{
printf("密码错误!请重新输入密码:\n");
}
}
break;
}
case 2:{
readuser();
insert_item(userlist, userinfo);
save_to_file(userlist);
break;
}
}
}
这个是我的控制台的图片,一直是这样,没有结果,没有提示报错
![图片说明](https://img-ask.csdn.net/upload/202002/09/1581214606_464333.png)
![图片说明](https://img-ask.csdn.net/upload/202002/09/1581214919_702020.png)