-1

我正在尝试制作这个密码验证程序,并且我在第一时间得到一个无限循环。它非常令人沮丧。我已经为此工作了大约一天半......该程序的目的是确保通行证至少有 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 ;
}
4

2 回答 2

0

如果你想要至少 6 个字符长,你需要<=这样你的 while 循环应该是 while(num <= 6).

于 2013-07-26T15:37:09.547 回答
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
于 2013-07-26T15:35:03.527 回答