输入密码时无限循环

时间:2013-07-26 15:24:38

标签: c++ string validation passwords infinite-loop

我正在尝试制作这个密码验证程序,并且我在第一次获得无限循环时。它非常令人沮丧。我已经在这一天工作了大约一天半...... 该计划的目的是确保通行证至少有6个字符长,并且还有一个上部,一个下部和一个数字。

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;


bool testPass(char []);
int main()
{
    char *password;
    int length; 
    int num; 

    cout << "Please enter how many characters you would like your\npassword to be.";
    cout << " Your password must be at least 6 characters long." << endl;
    cin >> num;


     while(num < 6)
     {
        cout << "Please enter a password length of at least 6 characters." << endl;
        cin >> num;
     }


    password = new char[num+1]; 


    cout << "Please enter a password that contains at least one uppercase letter, ";
    cout << "one\nlowercase letter, and at least one digit." << endl;


    cin >> password;


    length = strlen(password);



    while (length != num)
    {
        cout << "Your password is not the size you requested. ";
        cout << "Please re-enter your password." << endl;
        cin >> password;
        length = strlen(password);
    }

    if (testPass(password))
        cout << "Your password is valid." << endl;
    else
    {
        cout << "Your password is not valid. ";
        cout << "Please refer to the above warning message." << endl;
    }

    delete[] password;

    system("pause");
    return 0;
}



bool testPass(char pass[])
{
    bool aUpper = false,
         aLower = false,
         aDigit = false ;
    for ( int i = 0 ; pass[i] ; ++i )
        if ( isupper(pass[i]) )
            aUpper = true ;
        else if ( islower(pass[i]) )
            aLower = true ;
        else if ( isdigit(pass[i]) )
            aDigit = true ;
    if ( aUpper && aLower && aDigit )
        return true;
    else
        return false ;
}

2 个答案:

答案 0 :(得分:0)

int num; 
cin >> num;

上面的代码会询问一个数字并将其存储在num中。这不是您想要的,您需要将密码存储在字符串中,并在需要时检查长度和其他属性。

cin >> str;

如果发现任何空格字符,就会立即停止阅读,这不是我们想要的。

请查看http://www.cplusplus.com/doc/tutorial/basic_io/

解决方案可以是以下代码:

string password;
bool valid = false;

while (!valid) {
    getline(cin, password);
    valid = password_valid(password);
    if (!valid) {
        // display error message
    }
}

// password is valid

答案 1 :(得分:0)

如果你想要至少6个字符,你需要<=所以你应该循环 while(num <= 6)