我对C ++和这个论坛完全陌生。我尝试搜索代码并找到一段代码,但它不能像我想要的那样工作。我想要一个登录,检查txt文件的每一行,如果用户名和密码正确,则授予对系统的访问权。
string line = " ";
ifstream readfile("Login.txt");
string username, password, adminname, adminpass;
cout << "\nEnter Username: ";
cin >> username;
cout << "\nEnter Password: ";
cin >> password;
while (getline(readfile, line))
{
stringstream iss(line);
iss >> adminname >> adminpass;
//Login Success Function
if (username == adminname && password == adminpass)
{
cout << "\nLOGIN SUCCESSFUL!";
}
}
//Login Fail Function
{
int fail = 5;
while (fail > 0)
{
cout << "Error! Invalid Username and Password. Please reenter.\n";
cout << "You have " << fail << " tries left.\n";
cout << "\nEnter Username: ";
cin >> username;
cout << "\nEnter Password: ";
cin >> password;
fail--;
}
cout << "\nACCESS DENIED!";
}
txt文件包含第一行(admin123 password123),第二行(admin admin)。 如果我输入正确,登录工作正常,但如果我输入错误的用户名或密码,我只是停留在while循环中,直到它显示访问被拒绝,即使我输入正确的用户名和密码进行第二次尝试。
任何人都可以帮我解决这个问题吗?如果可能请包含评论(//),以便我能够从中学习。提前谢谢。
答案 0 :(得分:0)
由于你在评论中提到这是一项任务,我将保持这个非常一般。
在您的程序中,您提示一次输入用户名和密码,然后通读文件以查看是否匹配。
如果没有匹配,则在循环中再次提示输入用户名和密码,但不检查它们是否有效。这就是问题所在。每次获得新的用户名和密码时,请检查它们是否有效。
有(至少)两种可能的方法:
std::map
,因为它是直接访问,并且是最少量的代码,但是还有很多其他方法可以做到这一点。这是重新读取文件的可能方法。请注意,这主要是重新组织您已有的代码:
bool success = false; //use this as part of our loop condition
int fail = 5;
while (!success && fail > 0) //loop until we succeed or failed too much
{
//get the username and password
cout << "\nEnter Username: ";
cin >> username;
cout << "\nEnter Password: ";
cin >> password;
//open the file and see if we have a match
ifstream readfile("Login.txt");
while (getline(readfile, line))
{
stringstream iss(line);
iss >> adminname >> adminpass;
//Login Success Function
if (username == adminname && password == adminpass)
{
//we have a match, so set success to true so we exit the loop
success = true;
}
}
if (!success) //we did not find a match in the file
{
//so we output the message
cout << "Error! Invalid Username and Password. Please reenter.\n";
cout << "You have " << fail << " tries left.\n";
fail--;
}
}
//now we know if we had success or not, so report it
if (success)
{
cout << "\nLOGIN SUCCESSFUL!";
}
else
{
cout << "\nACCESS DENIED!";
}