双IF语句 - 只有第一个有效

时间:2014-08-12 22:20:16

标签: c++ if-statement

这是我的问题:该程序需要登录信息。用户名验证工作正常 - 当给出错误的用户名时,它将被拒绝,并要求用户重试。但是,当出现密码提示时,接受任何给定的字符 - 即使只是按ENTER键也会让你登录。任何人都可以发现我的错误吗?

int main()
{
    int i;
    int e;

    string x;
    string userName;
    string userPass;

    i = 1;
    e = 1;

    cout << "Please enter your information to login.\n";
    //First 'do' is so that the line "Please enter your info..." does not get repeated
    do
    {
        //This 'do' is to loop through the login process until successful
        do
        {
            cout << "Username: ";
            getline (cin, userName);

            //Checks for a successfully input username
            if (userName == "Fin")
            {
                cout << "Password: ";
                getline (cin, userPass);

                //Checks for a successfully input password
                // HERE'S WHERE THE PROBLEM IS
                if (userPass == "fin123");
                {

                    cout << "Login successful.\n" << "Press ENTER to exit.";
                    //Waits for user to hit the ENTER key before exiting
                    getline (cin, x);
                    if (x.empty())
                    {
                        return 0;
                    }
                }
                //If the password is incorrect, start the login loop over
                if (userPass != "financiero123")
                {
                    cout << "Incorrect password. Please try again.";
                    //Waits for user to press a key before starting over
                    cin.get();
                    e = 0;
                }
            }
            //If the username is incorrect, start the login loop over
            if (userName != "Financiero")
            {
                cout << "Incorrect username. Please try again.";
                //Waits for user to press a key before starting over
                cin.get();
                e = 0;
            }
        } while (e != 0);
        e = 1;
    } while (e != 0);

    return 0;
}

1 个答案:

答案 0 :(得分:6)

if (userPass == "fin123");
{
    // ...

条件后的分号关闭条件,所以剩下的就变成了一个匿名块。就好像你写了这个:

if (userPass == "fin123") { }
{
    // ...

因此无条件执行此行之后的块。

删除分号以纠正逻辑错误。

(使用-Wempty-body标志进行编译会发出警告。)

相关问题