(1) 实现用户注册 登录功能。控制台输入R,提示用户注册,请输入用户名 (只能包含字母和数字); 输入用户名 ,回车 提示请输入密码;用户名,密码(长度至少6个字符 只能包含 数字 字母), 实现注册功能(用户名 密码 写入文件1.txt中,格式 用户名|密码)。 (2) 输入L 提示用户登录 输入已注册的用户名 密码实现登录 用户名 密码都正确 提示登录成功, 提示:“请输入指令>>>” 否则提示登陆失败,请重新登陆。 用c#表示
时间: 2024-01-03 22:33:06 浏览: 38
以下是用C#实现用户注册和登录功能的示例代码:
```csharp
using System;
using System.IO;
public class Program
{
public static void Main()
{
Console.WriteLine("请输入指令(R-注册,L-登录):");
string command = Console.ReadLine();
if (command == "R")
{
Register();
}
else if (command == "L")
{
Login();
}
else
{
Console.WriteLine("无效的指令!");
}
}
public static void Register()
{
Console.WriteLine("请输入用户名(只能包含字母和数字):");
string username = Console.ReadLine();
if (!IsValidUsername(username))
{
Console.WriteLine("无效的用户名!");
return;
}
Console.WriteLine("请输入密码(至少6个字符,只能包含字母和数字):");
string password = Console.ReadLine();
if (!IsValidPassword(password))
{
Console.WriteLine("无效的密码!");
return;
}
string userData = username + "|" + password;
try
{
using (StreamWriter writer = new StreamWriter("1.txt", true))
{
writer.WriteLine(userData);
}
Console.WriteLine("注册成功!");
}
catch (Exception ex)
{
Console.WriteLine("注册失败:" + ex.Message);
}
}
public static void Login()
{
Console.WriteLine("请输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
try
{
using (StreamReader reader = new StreamReader("1.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] userInfo = line.Split('|');
if (userInfo.Length == 2 && userInfo[0] == username && userInfo[1] == password)
{
Console.WriteLine("登录成功!");
Console.WriteLine("请输入指令>>>");
return;
}
}
}
Console.WriteLine("登录失败,请重新登录!");
}
catch (Exception ex)
{
Console.WriteLine("登录失败:" + ex.Message);
}
}
public static bool IsValidUsername(string username)
{
foreach (char c in username)
{
if (!char.IsLetterOrDigit(c))
{
return false;
}
}
return true;
}
public static bool IsValidPassword(string password)
{
if (password.Length < 6)
{
return false;
}
foreach (char c in password)
{
if (!char.IsLetterOrDigit(c))
{
return false;
}
}
return true;
}
}
```
上述代码实现了在控制台中注册和登录功能。当用户输入 "R" 时,会提示用户注册信息并将用户名和密码写入到 "1.txt" 文件中,格式为 "用户名|密码"。当用户输入 "L" 时,会提示用户登录,并在 "1.txt" 文件中校验用户名和密码,如果匹配成功则登录成功,否则登录失败。
请注意,此示例仅供参考,实际应用中可能需要更严格的输入验证和错误处理机制。