2014-04-29 47 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++; 
}