所以我創建了一個能驗證密碼是否正確創建的程序。要通過驗證,用戶必須輸入6個或更多字符,至少包含一個小寫字母,一個大寫字母和一個數字。問題是我只能使用cstring(當然是cctype)庫而不是字符串庫。如果用戶創建一個不正確的密碼,如果他們成功地創建了一個好的密碼,然後有時(不知道爲什麼有時)它崩潰,程序運行良好。對此的回答,將有助於我鞏固我對指針的更多理解,即動態分配內存。因此,這裏是有問題的程序。我的程序有時會導致C++崩潰?
#include <iostream>
#include <cctype>
#include <cstring>
bool isVerifyAccepted(char*, int);
using namespace std;
int main() {
const int SIZE = 6;
char *userPass = new char[SIZE];
cout << "Verify you have a good password\na good password has to be at least six characters long\n"
<< "have at least on uppercase and one lowercase letter and at least one digit" <<endl <<endl;
cout << "enter a password below" <<endl <<endl;
cin >> userPass;
int userSizePass = strlen(userPass);
char testPassWord[userSizePass];
int count = 0;
while (count < userPass[count]) {
testPassWord[count] = userPass[count];
count++;
}
isVerifyAccepted(testPassWord, userSizePass);
delete[] userPass;
userPass = NULL;
//system("pause");
return 0;
}
bool isVerifyAccepted(char *pass, int size){
bool verify[3];
if(size <= 6){
cout << "Password is too short "<<endl;
return false;
}
for(int i = 0; i<size; i++){
if(islower(pass[i])){
verify[0] = true;
break;
}else{
verify[0] = false;
}
}
for(int i = 0; i<size; i++){
if(isupper(pass[i])){
verify[1] = true;
break;
}else{
verify[1] = false;
}
}
for(int i = 0; i<size; i++){
if(isdigit(pass[i])){
verify[2] = true;
break;
}else{
verify[2] = false;
}
}
if(verify[0] == false){
cout << "You need at least one lowercase letter" << endl;
}
if(verify[1] == false){
cout << "You need at least one uppercase letter" << endl;
}
if(verify[2] == false){
cout << "You need at least one digit" << endl;
}
if((verify[0] == true) && (verify[1] == true) && (verify[2] == true)){
cout << "You have a good password, you met the criteria " <<endl;
}
return verify;
}
***要通過驗證,用戶必須輸入6個或更多字符***,但您已經爲5個字符+空終止符分配了空間。 – drescherjm
它崩潰在哪裏?調試器應該指向特定的指令(行)。 –
當您在調試器中運行它時,它是否會崩潰(有時甚至是)?如果你不知道,因爲你還沒有嘗試......這應該是你發佈之前的一個步驟。除此之外...看到第一條評論,它告訴你爲什麼你遇到了未定義的行爲(這有時意味着崩潰 - 但它沒有定義,所以不一定會崩潰)。 – mah