2014-04-29 71 views
-1

我試圖創建一個從文件中導入的迷宮,然後放入一個載有bools矢量的矢量中。輸入到2D矢量中的迷宮遊戲

我的問題是我從文件中獲取了信息,但我不確定如何將它處理成2D矢量。在迷宮中,任何具有「+」的座標都是一條路徑,而其他任何東西(空白區等)都是一條牆。開始和結束位置是Location對象,但我還沒有編碼。

vector<vector<bool> > mazeSpec; 
string buffer; //holds lines while they are read in 
int length; //holds length of each line/# of columns 
Location start, finish; 

ifstream mazeFile("maze.txt"); 
if (!mazeFile) { 
    cerr << "Unable to open file\n"; 
    exit(1); 
} 

getline(mazeFile, buffer); // read in first line 
cout << buffer << endl; //output first line 
length = buffer.length(); //length now set so can be compared 

while (getline(mazeFile, buffer)) { 
    bool path = (buffer == "*"); 
    cout << buffer << endl; 
} 
+0

你需要提供一個完整的迷你樣本文件和所需的結果二維數組。也不清楚爲什麼你閱讀第一行並存儲它的長度以供以後比較 - 將它與* what *進行比較。您在描述中提及'+',但在代碼中使用了'*'。 –

回答

0

你應該用char填充它。 對於文件中的每一行,添加一行mazeSpec:

mazeSpec.resize(mazeSpec.size() + 1); 

對於每一個燒焦你閱讀,添加一列以mazeSpec你的行正在努力:

mazeSpec[i].push_back(buffer[j] == '*'); 

你」我會得到這樣的東西:

int i, j; 
vector<vector<bool> > mazeSpec; 
string buffer; //holds lines while they are read in 
int length; //holds length of each line/# of columns 
Location start, finish; 

ifstream mazeFile("maze.txt"); 
if (!mazeFile) { 
    cerr << "Unable to open file\n"; 
    exit(1); 
} 

getline(mazeFile, buffer); // read in first line 
cout << buffer << endl; //output first line 
length = buffer.length(); //length now set so can be compared 

mazeSpec.resize(1); 
for(j = 0; j < buffer.length(); j++) { 
    mazeSpec[0].push_back(buffer[j] == '*'); // or perhaps '+' 
} 

i = 1; 
while (!mazeFile.eof()) { // read in maze til eof 
    getline(mazeFile, buffer); 

    mazeSpec.resize(mazeSpec.size() + 1); 
    for(j = 0; j < buffer.length(); j++) { 
     mazeSpec[i].push_back(buffer[j] == '*'); // or perhaps '+' 
    } 

    cout << buffer << endl; 
    i++; 
}