提问者:小点点

函数中的Do-While循环


我只是在学习,所以请不要苛责我。我有个问题。我知道如何do do While循环。但今天我学到了关于函数的知识。所以我在函数中做了do-while循环,它是无限循环的。这只是个例子。我很开心,也很麻烦:请帮帮我!!如何停止永远的循环?

#include <iostream>
using namespace std;


void text()
{
    cout << "Log in to see the Menu. " << endl;
}


void lg()
{
    const string login = "el1oz";
    string input;

    cout << "Login > " << flush;
    cin >> input;

    do{
    if(login == input){
        break;
    }
    else{
        cout << "Try again." << endl;
    }
    }while(true);

    cout << "Correct Login! " << endl;
}   


void pw()
{
    const string password = "Mau01171995";
    string input1;

    cout << "Password > " << flush;
    cin >> input1;

    do{
        if(password == input1){
            break;
        }
        else{
            cout << "Try again. " << endl;
        }
    }while(true);

    cout << "Correct Passsword! " << endl;
}

int main() 

{
    text();

    lg();

    pw();

    return 0;
}

共1个答案

匿名用户

  1. 代码进入循环后,您不会更改输入。您应该将cin>>;在循环中输入
  2. 还要考虑何时使用while循环还是使用do while循环。在这种情况下,while循环更好。
  3. 您可能不应该使用使用命名空间std;(此处提供更多信息)。
  4. 您应该使用更具描述性的名称。
#include <iostream>
using std::cin;
using std::string;
using std::cout;
using std::flush;
using std::endl;


void printWelcome()
{
    cout << "Log in to see the Menu. " << endl;
}


void inputUser()
{
    const string login = "el1oz";
    string input;

    cout << "Login > " << flush;

    while(cin >> input){
        if(login == input){
            break;
        }
        else{
            cout << "Try again." << endl;
        }
    }

    cout << "Correct Login! " << endl;
}


void inputPassword()
{
    const string password = "Mau01171995";
    string input;

    cout << "Password > " << flush;

    while(cin >> input){
        if(password == input){
            break;
        }
        else{
            cout << "Try again. " << endl;
        }
    }

    cout << "Correct Passsword! " << endl;
}

int main()
{
    printWelcome();
    inputUser();
    inputPpassword();
    return 0;
}