簡體   English   中英

C++ 數組,表達式必須有一個常量值

[英]C++ arrays, expression must have a constant value

好的,所以我是編碼新手並且正在嘗試學習 C++。 我正在制作一個程序來驗證密碼有大寫、小寫和數字。 我覺得解決方案將是一個簡單的解決方案,但我終其一生都無法解決。

using namespace std;

    string password ="";
    cin >> password; 
  

我可以驗證這個罰款。 然后我想將密碼轉換為字符數組,以便我可以檢查密碼的每個字符。 我開始:

    char passwordHolder[password.length()];

但我收到錯誤:

表達式必須有一個常量值

從查看其他論壇的回復來看,我認為這與作為編譯器無法處理變量數組的 Visual Studio 有關,盡管我真的不明白這是如何/為什么發生的,或者如何解決這個問題。

另一篇文章建議使用new運算符,但我不完全理解如何以有效的方式將其實現到我的代碼中。

任何幫助表示贊賞。

啊我終於明白了。 感謝 user4581301 告訴我一個字符串已經是一個字符數組。 這個提示給了我如何解決問題的想法。

我實際上設法完全擺脫了新數組,而是搜索字符串。

而不是char passwordHolder[password.length()]; 我可以完全擺脫它。

我最初的計划是搜索passwordHolder數組:

for (int i = 0; i < password.length(); i++){
  if (isupper(passwordHolder[i])){
    hasUpper= true;
  }
  if (islower(passwordHolder[i])){
    hasLower= true;
  }
  if (isdigit(passwordHolder[i])){
    hasDigit = true;
  }
}
if (hasLower == true && hasUpper == true && hasDigit == true)
        return 1;

但是看到我不再需要passwordHolder數組,我可以改為使用password作為數組並執行以下操作:

for (int i = 0; i < password.length(); i++) {
        if (isupper(password[i]))
            hasUpper = true;
        else if (islower(password[i]))
            hasLower = true;
        else if (isdigit(password[i]))
            hasDigit = true;
    }
    if (hasLower == true && hasUpper == true && hasDigit == true)
        return 1;

感謝評論的人。 我已經堅持了大約 3 個小時,哈哈。

如果您在執行此任務時也遇到問題,我的完整解決方案在這里。 可能仍然很邋遢,但它有效:

#include <iostream>
#include <string>
using namespace std;


string password = "";
string confirmPassword = "";

bool hasDigit = false;
bool hasUpper = false;
bool hasLower = false;

int x = 0;

int confirm(string password, bool hasUpper, bool hasLower, bool hasDigit)
{

    for (int i = 0; i < password.length(); i++) {

        if (isupper(password[i]))
            hasUpper = true;
        else if (islower(password[i]))
            hasLower = true;
        else if (isdigit(password[i]))
            hasDigit = true;
    }
    if (hasLower == true && hasUpper == true && hasDigit == true)
        return 1;
}

int main(string password, bool hasUpper, bool hasLower, bool hasDigit) {

Start:

    cout << "please enter your password: ";
    cin >> password;
    cout << "please confirm your password: ";
    cin >> confirmPassword;

    while (password != confirmPassword || password.length() < 8) {

        cout << "Passwords do not match. Please enter your password again: ";
        cin >> password;
        cout << "Please confirm your password: ";
        cin >> confirmPassword;
    }
    
    x = confirm(password, hasUpper, hasLower, hasDigit);

    if (x == 1) {
        cout << "You have a good password";
    }
    else {
        cout << "You should have a password with 8 characters or more, a Capital letter, lowercase letter, and a number. Try again. \n";
        goto Start;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM