C# 如何允许用户保持输入用户名?
我想允许用户输入用户名。然后,用户名应存储在文件中(如果不存在,则创建该文件)。但是,如果文件中已经存在用户名,则用户应该会收到一个错误 完成后,用户应能够输入新用户名C# 如何允许用户保持输入用户名?,c#,visual-studio-2013,console-application,C#,Visual Studio 2013,Console Application,我想允许用户输入用户名。然后,用户名应存储在文件中(如果不存在,则创建该文件)。但是,如果文件中已经存在用户名,则用户应该会收到一个错误 完成后,用户应能够输入新用户名 while(true) { Console.WriteLine("Username: "); string uCreation = Console.ReadLine(); bool exists = false; foreach (string lines in File.ReadAllLine
while(true)
{
Console.WriteLine("Username: ");
string uCreation = Console.ReadLine();
bool exists = false;
foreach (string lines in File.ReadAllLines("Usernames.txt"))
{
if (lines == uCreation)
{
Console.WriteLine("Username already exists!");
exists = true;
break;
}
}
if (!exists)
{
File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine);
break;
}
}
我的问题是,我不知道如何不断地询问用户名
string fileName = ("Usernames.txt");
if (File.Exists(fileName))
Console.WriteLine("Username file already exists!");
else
Console.WriteLine("Username file was created!");
FileStream un = new FileStream("Usernames.txt",
FileMode.Create, FileAccess.Write);
StreamWriter kasutajanimed = new StreamWriter(un);
Usernames.Close();
Console.WriteLine("Username: ");
string uCreation = Console.ReadLine();
bool exists = false;
foreach (string lines in File.ReadAllLines("Usernames.txt"))
{
if (lines == uCreation)
{
Console.WriteLine("Username already exists!");
exists = true;
break;
}
}
if (!exists)
{
File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine);
}
你只需要另一个循环,让他们输入另一个用户名
while(true)
{
Console.WriteLine("Username: ");
string uCreation = Console.ReadLine();
bool exists = false;
foreach (string lines in File.ReadAllLines("Usernames.txt"))
{
if (lines == uCreation)
{
Console.WriteLine("Username already exists!");
exists = true;
break;
}
}
if (!exists)
{
File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine);
break;
}
}
如果每次都以这种方式搜索文件,则每个条目都将为O(n)。我认为更好的方法是在文件中保留一个包含所有用户名的集合。因此,在打开文件时,将文件中的所有用户名添加到哈希集。然后,您只需调用hashSet.Contains(username)来检查用户名是否在O(1)时间内存在 对于持续询问用户,可以使用while-true循环。像这样
while (true) // Loop indefinitely
{
Console.WriteLine("Username: "); // Prompt
string line = Console.ReadLine(); // Get string from user
if (hashSet.Contains(line)) {
Console.WriteLine("Username Already in Use");
continue;
}
if (line == "exit") // have a way to exit, you can do whatever you want
{
break;
}
// Here add to both file and your HashSet...
}
欢迎来到我们的社区。你需要调整你的问题,这样你就可以问一个特定的问题。告诉我们什么不起作用,或者你需要帮助的代码的哪一部分。是的,但是现在我想不出一个方法来继续使用代码来要求X的东西。否则谢谢!当它要求输入用户名时,您输入一个,它会接受用户名并要求输入一个新的用户名,而不是继续使用代码。当您两次输入相同的用户名时,它表示该用户名已经存在,然后继续输入其余的代码。编辑你似乎把它修好了,这似乎对我有用!谢谢!:)@CrimzonWeb既然答案对您有帮助,您应该将其标记为已接受。也考虑一下投票的结果;