正如我所理解的问题,你希望能够从文件中读取节点的描述并将它们存储在内存中的数据结构中。看起来像一个文字冒险地图。
我复制你的迷宫游戏地图到名为文本文件“maze.dat”
这里有一个简单的程序,解析maze.dat文件,一行行,存储每个行成一个用户定义的数据称为节点的结构。然后将每个节点放入另一个称为矢量的数据结构中。
在程序结束时,我已经打印出矢量中的每个节点,以便您可以看到它与原始输入文件相匹配。这是我的例子:
#include <iostream>
#include <fstream>
#include <vector>
// storing each node in a data structure
class Node
{
public:
Node(char name, char north, char east, char south, char west)
{
this->name = name;
this->north = north;
this->east = east;
this->south = south;
this->west = west;
};
char name;
char north;
char east;
char south;
char west;
};
// function to print out a node
void print_node(Node n)
{
std::cout << n.name << " " << n.north << " " << n.east << " " << n.south << " " << n.west << " " << std::endl;
}
int main(int argc, const char * argv[])
{
// first off let's read in our maze data file
std::ifstream maze_file("maze.dat");
// create somewhere to store our nodes
std::vector<Node> nodes;
// check that we opened the file, then parse each line
if(maze_file.is_open())
{
while(maze_file.good())
{
// temporary node_data for each line in the file
std::string node_data;
// read the current line
getline(maze_file, node_data);
// parse the line into tokens (e.g. A, ,*, ,B, ,*, ,*)
std::vector<char> tokens(node_data.begin(), node_data.end());
// strip out the blanks ' ' (e.g. A,*,B,*,*)
tokens.erase(std::remove(tokens.begin(), tokens.end(), ' '), tokens.end());
// there should be 5 tokens for a node description
if(tokens.size() == 5)
{
Node node(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4]);
nodes.push_back(node);
}
else
std::cout << "There weren't 5 tokens in the node description, there were: " << tokens.size() << std::endl;
}
// clean-up the open file handle
maze_file.close();
}
else
std::cout << "Unable to open file maze.dat";
// now we can prove that we've stored the nodes in the same way as they were in the file
// let's print them out from the vector of nodes
std::for_each(nodes.begin(), nodes.end(), print_node);
return 0;
}
这是一个非常简单的方法来将文件转换成数据结构。这对于加载文件非常有用,您可以创建一种保存地图的方式,从而构建地图创建者程序。
这对于在实际游戏中实际使用迷宫地图可能没有多大帮助。根据你是否想要往北,东,南,西旅行,你很可能想要找回相关的房间。为此,您将需要使用std :: map构建一个图形数据结构,如前所述Str1101
您是否在问如何将节点链接在一起? –
我不确定我在问什么。我想是这样。 我正在阅读文本文件中的所有信息,但一旦它到达行的末尾,我希望保留当前保存的信息,然后为下一行创建一个类型为Node的新对象。 – sakau2007
也许你会发现有用的答案给予下一个问题:http://stackoverflow.com/questions/2323929/istringstream-how-to-do-this – Str1101