#include <stdio.h>
#include <string.h>
typedef struct fre
{
char name[10];
char id [20];
char password[30];
char phone[20];
char age[5];
}friend;
int main()
{
FILE *fp;
friend myfree[30];
char user_input_id[20];
char user_input_pw[20];
printf("[로그인 UI] \n");
int switch_1 = 1;
while(switch_1==1)
{
printf("ID: ");
scanf("%s", user_input_id);
printf("유저가 입력한 아이디: %s\n", user_input_id);
fp = fopen("all_users.bin", "rb"); // 파일 읽기
int break_ = 0; // 중복일때 반복을 안하게 만드는 변수
for (int i = 0; i <= 2; i ++)
{
fread((void*)&myfree[i], sizeof(myfree[i]), 1, fp);
if (strcmp(user_input_id, myfree[i].id) == 0)
{
printf("PW: "); // 입력한 아이디가 존재하면 비번 입력
scanf("%s", user_input_pw);
if (strcmp(user_input_pw, myfree[i].password) == 0) // 비번 맞으면
{
printf("로그인 되었습니다.\n");
switch_1 = 0;
}
else
{
printf("비밀번호가 틀렸습니다.\n");
printf("비밀번호를 다시 입력해주세요.\n");
break;
}
}
else
{
printf("없는 아이디 입니다.\n");
printf("다시 입력해주세요.\n");
break;
}
}
}
printf("로그인 후 메인화면");
}
비번을 입력할때 아이디가 맞는다는 선제조건이 있어야하니까
아이디 확인 후 그 안에 if절을 넣어서 비번 검사를 하려고 했는데
비번이 틀렸을 때, 비번이 아니라 아이디를 또 다시 입력하라고 하니까 답답했다.
그래서 while문을 2개를 만들었는데
이렇게하면 문제가 똑같은 비번을 쓰는 다른 유저가 있을 때 겹치니까
어떤 유저의 비번과 검사해야하는지 명확하지가 않아서 while문을 따로 쓰는건 안될거같다.
int switch_2 = 1;
while(switch_2 == 1) // 비번 확인
{
printf("PW: "); // 입력한 아이디가 존재하면 비번 입력
scanf("%s", user_input_pw);
for (int i = 0; i <= 2; i ++)
{
if (strcmp(user_input_pw, myfree[i].password) == 0) // 아이디가 들어있고,
{
printf("로그인 되었습니다.\n");
switch_2 = 0;
break;
}
else
{
printf("비밀번호가 틀렸습니다.\n");
printf("다시 입력해주세요.\n");
break;
}
}
}
최종 완성된 로그인 기능
#include <stdio.h>
#include <string.h>
typedef struct fre
{
char name[10];
char id [20];
char password[30];
char phone[20];
char age[5];
}friend;
int main()
{
FILE *fp;
friend myfree[30];
int check_id;
char user_input_id[20];
char user_input_pw[20];
printf("[로그인 UI] \n");
int switch_1 = 1;
while(switch_1==1)
{
printf("ID: ");
scanf("%s", user_input_id);
printf("유저가 입력한 아이디: %s\n", user_input_id);
fp = fopen("all_users.bin", "rb"); // 파일 읽기
int break_ = 0; // 중복일때 반복을 안하게 만드는 변수
for (int i = 0; i <= 5; i ++)
{
fread((void*)&myfree[i], sizeof(myfree[i]), 1, fp);
if (strcmp(user_input_id, myfree[i].id) == 0) // 아이디가 존재하면 비번 입력
{
printf("아이디가 존재합니다.\n");
check_id = i;
switch_1 = 0; // 아이디 반복문 탈출
break;
}
else
{
printf("없는 아이디 입니다.\n");
printf("다시 입력해주세요.\n");
break;
}
}
}
int switch_2 = 1;
while(switch_2 == 1) // 비번 확인
{
printf("PW: ");
scanf("%s", user_input_pw);
if (strcmp(user_input_pw, myfree[check_id].password) == 0) // 아이디가 들어있고,
{
printf("로그인 되었습니다.\n");
switch_2 = 0; // 비번 반복문 탈출
break;
}
else
{
printf("비밀번호가 틀렸습니다.\n");
printf("다시 입력해주세요.\n");
break;
}
}
printf("로그인 후 메인화면");
}
유저가 입력한 아이디가 몇번째인지 check_id 변수에 저장하고
비밀번호 확인하는 반복문에서 해당 check_id 변수에 저장된 비밀번호를 확인해서
유저가 입력한 비밀번호가 맞는지 검사한다.
이로써 같은 비번을 갖고있는 다른 유저와 구별할 수 있게 되었다.