gpt4 book ai didi

c++ - 在迷宫的 txt 文件中查找特定字符

转载 作者:行者123 更新时间:2023-11-28 06:24:15 26 4
gpt4 key购买 nike

我正在尝试设置一个从文本文件获取迷宫入口的函数,txt 文件中的字符是“E”。这需要用作播放器的起始位置,但我不确定如何识别文本文件中的某个字符。

这是读取文件并打印它的代码,但我不确定如何选择入口并为其赋值。

void Floor::printToScreen()
{
ifstream f("FloorA.txt");
string str;
int cols = 0;
int rows = 0;

char maze[20][30];

int line = 0;
while(getline(f, str)){
const char * chars = str.c_str();
for(int i = 0; i<str.length(); i++){
maze[line][i] = chars[i];
}
cols = str.length();
line++;
rows++;
}
for (int i=0; i<line; i++){
for(int j=0; j<rows; j++){
cout << maze[i][j] << "";
}
cout << endl;
}
cout << "Rows: " << rows << " Columns: " << cols;
}

FloorA txt 文件:

##############################
# K #
# ############## ### ### # #
# K # # #C# #K# # #
# ######### # A # # # # # # #
# K # # # #
# ############D#####D####### #
# #
# C G C #
# #
# ######D##############D#### #
# # C #K# # #
# #### ######## # # # #
# #K # # ### # # #### #
# # ## # #### # # # # # #
E # ## # # ### # # #### # #
# # # #K D # #
# #D#### ################### #
# K #
##############################

这在另一篇文章中进行了简要讨论,但请不要将其标记为重复,因为我仍然对实现感到困惑,所以我想在这里问一个更具体的问题。

最佳答案

试试这个:

bool entrance_found = false;
unsigned int entrance_row = 0;
unsigned int entrance_column = 0;
for (row = 0; row < MAX_ROWS; row++)
{
for (column = 0; column < MAX_COLUMNS; ++column)
{
if (maze[row][column] == 'E')
{
entrance_found = true;
entrance_row = row;
entrance_column = column;
break;
}
}
if (entrance_found)
{
break;
}
}

这是搜索矩阵或二维数组的标准用法。

请注意当找到'E' 时,入口的行和列是如何保存到entrance_rowentrance_column 中的。

变量entrance_found 用于退出外层循环。虽然不是必需的,但确实可以节省时间。

关于c++ - 在迷宫的 txt 文件中查找特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com