【解決方法】const 変数を持つ bool 関数を呼び出すにはどうすればよいですか?

プログラミングQA


2 つの const 変数を持つこの bool 関数を呼び出そうとしていますか?
変数の順序を変更してさまざまな方法を試しましたが、何も機能していないようです。

私が試したこと:

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

void displayMenu();
bool verify(const char, const int);


int main(){

	displayMenu();
	const int SIZE = 30;
	char pwd[SIZE];
	cout << "\n\nEnter your password: ";
	cin.ignore();
	cin.getline(pwd, SIZE);

	verify(pwd[SIZE], SIZE);

	//terminate
	return 0;
}

void displayMenu()
{
	const char FILL  = '+';
	const int  WIDTH = 60;
	cout << setfill(FILL) << setw(WIDTH) << "" << endl;
	cout << "Welcome to my password verifier and strength score program!\n";
	cout << "You password must meet all of the following conditions: \n";
	cout << "\t1. Contain at least twelve characters\n";
	cout << "\t2. Contain at least one lowercase letter\n";
	cout << "\t3. Contain at least one uppercase letter\n";
	cout << "\t4. Contain at least one digit\n";
	cout << "\t5. Contain at least one punctuation mark\n";
	cout << "\t6. Cannot contain any whitespace\n";
	cout << setfill(FILL) << setw(WIDTH) << "" << endl;

}
bool verify(const char pwd[], const int SIZE)
{
	for (unsigned i = 0; i <strlen(pwd); i++){
		 return (isdigit(pwd[i]));

	}
	return true;
}

解決策 1

[update]
おっと、私はそれを見落としました(ありがとう、 グリフ)

関数宣言は(もちろん)その定義と一致する必要があるため、宣言する必要があります verify、 道 グリフ 指摘した:

C++
bool verify(const char pwd[], const int SIZE);

[/update]

大雑把に言えば、 const 関数パラメータの on は、渡された値が関数自体によって変更されないという単なる約束です。 したがって、次のコードは正常に機能します

C++
int main()
{
  char password[] = "fooboogoo";
  cout << "verify(password) " << verify(password, sizeof(password)) << "\n";
}

そうは言っても、あなたの verify 関数は不完全で、間違っている可能性があります。

解決策 2

C++ では、配列は 0 から始まるインデックスを使用します。そのため、3 つの要素を持つ配列の有効なインデックスは 0、1、および 2 のみです。
あなたのコード:

	char pwd[SIZE];
...
	verify(pwd[SIZE], SIZE);

SIZE が 3 の場合、4 番目の要素を渡そうとします。

あなたがする必要があるのは、実際の宣言と一致するように前方参照を変更し、ポインタを最初の要素に渡すことです:

bool verify(const char[], const int);


int main(){
...
	char pwd[SIZE];
...
	verify(pwd, SIZE);
...
}

bool verify(const char pwd[], const int SIZE)

解決策 3

関数の署名をに変更します

C++
bool verify(const char *, const int SIZE)

これで完了です。

解決策 4

また、 const 整数パラメータへの修飾子は不要です。 値によって渡されるため、元の変数のコピーがスタックにプッシュされたため、元の変数を変更することはできません。 文字ポインタ パラメータには、 const 修飾子は、ポインターが関数に渡されるため、ポインターが指すデータが変更される可能性がありますが、そのアイテムを定数にすることでそれを防ぐことができます。

コメント

タイトルとURLをコピーしました