【发布时间】:2015-05-23 03:39:18
【问题描述】:
我正在尝试了解有关 C++ 的更多信息,并且正在制作(非常简单的)2D 地图编辑器。我目前有一个运行良好的系统,但我正在尝试通过使用标签来改进。
我想要完成的事情
我希望能够加载一个文本文件,并让它在一个关卡中存储我可能需要的所有数据(包括但不限于:瓷砖、背景、对象、播放器等)。这些文本文件将由我的地图编辑器生成,因此我可以完全控制它们的创建方式和结构。 虽然这不是一个学校项目,但我正在尝试更多地了解 C++,所以我宁愿使用尽可能少的依赖项(我目前只使用 SFML,但我认为这不相关为此),因此我不使用现有的 XML 解析器。
//Call to my parser
getTagContents("Resources/xmltester.txt", "mytag");
//
void getTagContents(std::string fileToBeParsedLocation, std::string tagName)
{
int lineNumberToFindTagName = 0;
int lineNumberToFindTagNameEnd = 0;
std::vector<int> tagsLine;
std::vector<int> tagsPos;
std::vector<std::string> tagContents;
std::string tempLine;
std::fstream fileToBeParsed(fileToBeParsedLocation);
if (fileToBeParsed.is_open())
{
while (!fileToBeParsed.eof())
{
while (std::getline(fileToBeParsed, line))
{
//Opening tag
if (line.find("<" + tagName + ">") == -1)
{
lineNumberToFindTagName++;
}
else
{
std::size_t pos = line.find("<" + tagName + ">");
std::cout << "Found tag " << tagName << " opening at line " << lineNumberToFindTagName << " at position " << pos << std::endl;
tagsLine.push_back(lineNumberToFindTagName);
tagsPos.push_back(pos);
lineNumberToFindTagName++;
//Test
//std::getline(fileToBeParsed, tempLine);
//std::cout << tempLine;
//This returns really strange values
}
//Closing tag
if (line.find("</" + tagName + ">") == -1)
{
lineNumberToFindTagNameEnd++;
}
else
{
std::size_t pos = line.find("</" + tagName + ">");
std::cout << "Found tag " << tagName << " closing at line " << lineNumberToFindTagNameEnd << " at position " << pos << std::endl;
tagsLine.push_back(lineNumberToFindTagNameEnd);
tagsPos.push_back(pos);
lineNumberToFindTagNameEnd++;
}
}
}
//Size of tagContents will always be half of either tagsLine or tagsPos (it doesn't matter which)
for (int i = 0; i < tagsPos.size()/2; i++)
{
for (int j = 0; j < tagsLine[i]; j++)
{
//I think this is where most of the stuff I need to add should go
}
std::getline(fileToBeParsed, tempLine);
std::stringstream stream(tempLine);
std::cout << "Line contents: " << tempLine << "<>" << std::endl;
}
}
for (int i = 0; i < tagsPos.size(); i++)
{
std::cout << tagsLine[i] << "." << tagsPos[i] << std::endl;
}
getchar();
getchar();
}
问题是什么
这可能主要是由于我的无能,但我不知道如何使用我知道标签的行和位置值这一事实来在它们之间进行阅读。这应该是微不足道的,但我想不出一种方法来确保我可以正确读取任意数量的标签......
有什么想法吗? (提前致谢)
【问题讨论】:
-
结束标签呢?知道开始标签的“>”和结束标签的“fstream 的
get()函数读取它们之间的内容。要在 '>' 字符上设置光标位置,您可以使用seekg()函数。 -
就我个人而言,我不确定 XML 是这里的最佳选择。在您更熟悉 C++ 中的基本解析函数如何工作之前,创建一个更简单的格式可能会更好。与游戏本身的数据存储方式非常相似。
-
Amadeusz,我想过这样的方法,但我担心我不能阅读超过一行。我要存储的数据之一是我的地图本身,虽然我会在阅读文件后知道它有多大,但它可能会很大(不确定硬件限制可能是什么,但我我希望它甚至可能每边都有几十万)。如果这根本不可能,我可以尝试另一种方法。