为什么我一直在无限循环?

时间:2014-04-26 14:45:09

标签: c++ loops infinite-loop

即使在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 << "\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;
}

1 个答案:

答案 0 :(得分:2)

while将继续循环,直到用户名不是&#34; asqdf&#34;并且密码不是&#34; 123&#34;并且代码从不要求新的用户名和&amp;密码,所以它将循环到无限。此外,每次循环迭代时,您都不会递增x,因此5次最大尝试代码将永远不会运行。

最后一个提示 - 如果您的方法不需要返回,则可以返回类型void。您可以使用break语句,而不是返回退出do-while。