2014-04-26 44 views
-3

即使在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 << "\n\nThank 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 << "\n\nYou have exceeded the 5 retry limitations......\n"; 
      Sleep(4000); 
      cout << "Exiting program...."; 
      Sleep(5000); 
      return 0; 
     } 
    }while(password != "123" && username != "asdqw"); 
    return 0; 
} 
+2

你在哪裏得到while循環內的輸入? –

+0

你必須做'cin >>密碼;'在循環中如果你想要終止。 – yakoudbz

+0

我以任何方式修復了THX – user2782625

回答

2

while會不斷循環,直到用戶名不是「asqdf」,密碼是不是「123」,代碼永遠不會要求一個新的用戶名&密碼,所以它會一直循環到無限。此外,每次循環迭代時,您都不會增加x,所以5次嘗試的最大代碼將永遠不會運行。

只是最後一個提示 - 如果您的方法不需要返回,您可以使返回類型void。您可以使用break聲明,而不是返回退出執行時間。