即使在do-while循环中,我也一直处于无限循环中!
我做错了什么?我什么都试过了,但还是想不通。有什么帮助吗?
这是我的代码:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
//function prototypes
//prototype for IsAccessible
int IsAccessible(string username, string password);
//prototype for menu
void menu();
int main()
{
string username;
string password;
//make user to login
cout << "Enter username : ";
getline(cin, username);
cout << "nEnter Password : ";
cin >> password;
IsAccessible(username, password);
cout << "Thank you for logging in!!";
cin.ignore();
cin.get();
return 0;
}
//function definitions
//definition for IsAccesible
int IsAccessible(string username, string password)
{
//check if user entered correct details
do
{
int x = 0;
if(password == "123" && username == "asdqw")
{
cout << "nnThank you for loggin in John!";
break;
}
//if user entered wrong details
else if(password != "123" && username != "asdqw")
{
cout << "nYou have either entered a wrong password or username.n";
cout << "Please retry.";
}
//if user exceeds limitation
if(x == 5)
{
cout << "nnYou have exceeded the 5 retry limitations......n";
Sleep(4000);
cout << "Exiting program....";
Sleep(5000);
return 0;
}
}while(password != "123" && username != "asdqw");
return 0;
}
while
将保持循环,直到用户名不是"asqdf",密码不是"123",并且代码从不要求新的用户名&密码,所以它将一直循环到无穷大。此外,您不会在每次循环迭代时递增x
,因此5最大尝试代码永远不会运行。
最后一个提示-如果您的方法不需要返回,您可以将返回类型设置为void
。您可以使用break
语句,而不是返回以退出dowhile。