C语言编程:实现用户的注册和登录

Python018

C语言编程:实现用户的注册和登录,第1张

模拟用户注册和登陆可以用文件来保存用户名和密码。注册就是向文件里写,用if判断两次密码是否一致。连续三次,可以有一个变量,每次输入加一,变量大于三就提示登陆不成功。用户名不对,那你就把你输入的用户名和文件里的用户名是否一致。

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

bool search(char id[], char pass[]) {

FILE *fp

char tid[10], tpass[10]

fp = fopen("c:\\data", "r")

while (!feof(fp)) {

fscanf(fp, "%s%s", tid, tpass)

if (strcmp(tid, id)==0 &&strcmp(tpass, pass)==0) {

fclose(fp)

return true

}

}

fclose(fp)

return false

}

bool login() {

char id[10], pass[10]

printf("Login\nPress the id: ")

scanf("%s", id)

printf("Press the password: ")

// 可以自行将password处理成*号, 如果不会可以发信给我

scanf("%s", pass)

printf("-----------------------")

if (search(id, pass))

return true

else

return false

}

void _add(char id[], char pass[]) {

FILE *fp

fp=fopen("c:\\data", "a")

// 在写入文件时可以按一定的排序方式插入,可减少以后Login时的search时间

fprintf(fp, "%s %s\n", id, pass)

fclose(fp)

}

void regis() {

char id[10], pass[10], tpass[10]

printf("Register\nPress the id: ")

scanf("%s", id)

while (true) {

printf("Press the password: ")

scanf("%s", pass)

printf("Press the password again: ")

scanf("%s", tpass)

if (strcmp(pass, tpass) != 0)

printf("The passwords you pressed are not the same!\n")

else

break

}

_add(id, pass)

printf("-----------------------Register successfully!\n")

}

void init() {

FILE *fp

if ((fp=fopen("c:\\data", "r")) == NULL) { // 注意,一定要有个名叫data(没有扩展名)的合法文件在C盘根目录

printf("---------File is not exist\n")

system("pause")

exit(0)

}

else

fclose(fp)

}

int main(void){

int command

init() // 检查data文件在不在

while (true) {

printf("-----------------------(Login: 1 Register: 2 Exit: 3)\n")

scanf("%d", &command)

printf("-----------------------\n")

// 这里可以编写command的检测语句

if (command == 3)

break

else if (command == 1) {

if (!login())

printf("ID is not exist or password is wrong!\n")

else

printf("Login successfully!\n")

}

else

regis()

}

return 0

}

搞定了。。。我是用成功了的。。。如果有问题就发信给我。。。。