私の現在の C++ のバックグラウンドは、大学レベルのコースを 1 学期受講したことです。
if-else ステートメント内で割り当てた値をその外に保持する方法を理解するのに苦労しています。事前に外部で宣言し、ポインターを使用してメモリアドレス自体を処理する場合、それは公正なゲームになると考えましたが、明らかにそうではありません。
今のところ私の「MAZE」ファイル:
. # # # # # #
. . . . . # #
# . # # . # #
# . # # . . #
# . . # # . #
# . # # . . #
# . # # . # #
. . . # . . .
# # . . . # #
そして、これが私の maze.h ファイル内にあるもので、コンストラクターを定義しています。まだほとんどのプログラムに慣れていませんが、私の main.cpp は既にテキスト ファイルの迷路の寸法の計算を処理しており、それから呼び出します。
Maze *testMaze = new Maze(rows,columns);
私の maze.h ファイルには bool maze[0][0] がプライベート メンバーとしてリストされています。コードの最初の実行時にはまだ迷路のサイズを知る方法がないため、0 に設定されています。コードを実行してサイズを計算し、行と列をパラメーターとして Maze コンストラクターに渡します。
パラメーターを持つ私の maze.cpp ファイルのコンストラクター:
Maze::Maze(int rows, int columns)
{
string mazeRow="";
int roIndex=0; //Row Index
int coIndex=0; //Column Index
bool maze[rows][columns];
bool* target = NULL;
ifstream input;
input.open("MAZE",ios::in);
if(input)
{
while (getline(input, mazeRow))
{
//Testprint this row of the maze.
cout << mazeRow << endl; //mazeRow is the data in that row of the text file.
//Store each non-space value.
for (coIndex=0; coIndex<mazeRow.length(); coIndex++) //For each character in that row...
{
char check=mazeRow[coIndex];
target = &maze[roIndex][coIndex];
if (check=='.') //Path
{
*target=true;
cout << *target << " "; //These print statements print correctly.
}
else if (check=='#') //Wall
{
*target=false;
cout << *target << " "; //These print statements print correctly.
}
else if (check==' ') //Space
{
//ignore spaces
}
else //For all other cases, an invalid character is present.
{
cout << "Invalid character detected." << endl;
}
cout << *target << " "; //For some odd reason, this line BY ITSELF doubles up print. Ex. instead of printing 1 1 0 1 0, it would print 1 1 1 1 0 0 1 1 0 0.
}
cout << "End of row." << endl;
roIndex++;
}
}
input.close();
cout << "Storage completed." << endl;
for (int i=0; i<rows; i++)
{
cout << "Row " << i << endl;
for (int j=0; j<columns; j++)
{
/* This is the print test to see if the values
are retained outside of the first block.
None of them print the maze file properly.
*/
if (maze[i][j] == true)
cout << maze[i][j] << "\t" << "." << "\t";
if (maze[i][j] == false)
cout << maze[i][j] << "\t" << "#" << "\t";
cout << "Column " << j << endl;
}
cout << "End of row." << endl;
}
cout << "Verification completed." << endl;
}
こちらで質問するのは初めてなので、わからないことがあれば教えてください。
ここにアップデートを載せたかっただけです。結局のところ、私は過度にストレスを感じていたか、睡眠不足か、またはその両方だった. このコードを数時間置いて、もう一度見直してみたところ、コードに非常に多くの論理エラーが見つかりました。これには、特定の変数が存在する理由やそれらが何のために使用されているかを忘れたり、すべてを明確に考えていなかったりすることが含まれますが、これらに限定されませんループ内でのインクリメント (++) の後遺症、またはそのようなずさんなミス。以下の回答/コメントのいくつかを取得し、自分のコードの理解を更新して、これらのエラーを修正するのに役立ちました. できたら、できれば完成したコードを提供します。
問題を解決しました。数時間以内に自己回答し、実際に何が起こったのかを説明できるようになります.