簡體   English   中英

如何檢查數組中的每個元素?

[英]How to check each element in array?

我正在嘗試分析迷宮游戲的chars txt文件中放置到數組中的每個元素。 必須檢查數組,以便我們確定迷宮中牆壁的位置,玩家的位置,幽靈,鑰匙和梯子,入口等。因此,我需要檢查某些字符(例如#,P,K,D,G ,E)。 我不確定該如何設置?

以下是獲取Floor文件並將每個字符放置在稱為tile的數組中的函數。

const int ROWS = 20;

void Floor::Read (const char * filename)
{
size_t row = 0;
ifstream input(filename);

while (row < ROWS && input >> tiles[row++]);

}
void Game::readFloors()
{
m_floor[0].Read("FloorA.txt");
m_floor[1].Read("FloorB.txt");
m_floor[2].Read("FloorC.txt");

}

這是每個字符的樓層之一:

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

具有上述功能的兩個類的頭文件:

class Floor {
char tiles[20][30]; 
void printToScreen();
public:
Floor();
void Read (const char * filename);
};

class Game {
private:
Floor m_floor [3];
vector<Character> characters; 
public:
void readFloors();
};

尋找類似的問題,但大多數都沒有分析許多不同的選擇。 謝謝您的幫助!

您可以在for循環內使用for循環,一個用於檢查數組中的列,另一個用於檢查行。 他們只是檢查每個元素是否等於k,c,g等。

我整理了一個簡單的閱讀器,將地圖(根據您的示例)放入一個矩陣以供您使用。

#include <iostream>
#include <fstream>
#include <string>

std::ifstream f("/path/../txt.txt");
std::string str;

int cols = 0;
int rows = 0;

char mat[100][100];

int main(){
    int line = 0;
    while(std::getline(f, str)){
        const char * chars = str.c_str();
        for(int i=0; i<str.length(); i++){
            mat[line][i] = chars[i];
        }

        cols = str.length();
        line++;
        rows++;
    }

    for(int i=0; i<line; i++){
        for(int j=0; j<rows; j++){
            std::cout<<mat[i][j]<<" ";
        }
        std::cout<<std::endl;
    }
    std::cout<<"Cols: "<<cols<<" Rows: "<<rows;
    return 0;
}

這樣,您只需執行簡單的角色比較,即可通過兩點坐標獲得每個玩家,牆塊等的位置。

暫無
暫無

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

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