如何在C++中读取自定义格式的文本文件
How to read custom format text file in C++
我正在写小游戏。我想从.txt文件中读取对象位置。我想写一个代码,读取像这样的文件(从.txt):
rock01
400.0 100.0 100.0
500.0 200.0 200.0
600.0 300.0 200.0
palm01
500.0 200.0 200.0
float 1是要创建的对象的x,第二个是y,第三个是z。名称(如"rock01")是要创建的对象的名称。
我的想法是读取对象名称,然后当下一行包含坐标而不是对象名称时,用这个坐标创建新对象。
所以上面的代码应该创建3块石头和一个手掌。
我的代码
std::fstream file;//.txt file
file.open(filename, std::ios::in);
std::string word;//name of the object
while(file >> word)
{
if(word == "rock01")
{
//and here I don't know how to read coordinates until next line is string
//so I read first...thing, and if it is float it creates new rock
float x;
while(file >> x)
{
rocks = new D_CRock;
rocks->position.x = x;
file >> rocks->position.y >> rocks->position.z
}
}
else if(word == "palm01") {
}
}
这个代码很破旧,但只适用于第一个对象(如果我把代码放成这样,它只会创建3个岩石:
rock01
400.0 100.0 100.0 4.0 170.0
500.0 200.0 200.0 4.0 0.0
rock01
600.0 300.0 200.0 4.0 90.0
rock01
400.0 100.0 400.0 1.0 170.0
它只会产生2块石头,而忽略其余的。
如何在不移动迭代器的情况下读取下一个序列(从一个空间到另一个空间,如"file>>someWord或someFloat",而不是字符)?如何读取这个序列的类型(检查它是浮动的还是只有字符串)?
我想知道怎样才能有效地做到这一点。
感谢
查看您的输入文件,您可能想要执行以下操作:
- 对于每条线路
- 检查非数字字符
- 如果找到,启动一个新对象
- 否则,解析坐标并创建一个新实例
有很多不同的方法可以做到这一点,下面大致展示了逻辑。
// Example program
#include <iostream>
#include <string>
#include <fstream>
bool contains_letter(std::string const& name)
{
// There are many other ways to do this, but for the sake of keeping this answer short...
return name.find_first_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ") != std::string::npos;
}
int main(int argc, char* argv[])
{
std::ifstream file;
file.open("filename.txt");
// ...
while (!file.eof())
{
std::string line;
std::getline(file, line);
if (contains_letter(line))
{
// ... Start a new object
}
else
{
// ... Parse the coordinates and add an instance
}
}
// ...
}
相关文章:
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?
- QT 标签 setText() 同时保留文本格式
- 输出使用 cout 转换为 ASCII 的文本时输出格式不正确,C++
- 如何设计对象以不同方式设置文本格式
- 使用文本格式来记录QT
- 如何将percision格式复制到文本文件
- C :如何从格式的文本文件中读取许多数据到程序中
- 使用无符号字符设置文本格式
- 阅读文本格式不一致
- 随机访问文件格式,用于分层组织的二进制文件和文本文件
- 要求文本编辑,文本格式
- 将Boost序列化文本存档转换为结构化格式
- 在Combobox中选择项目中的格式文本
- 读取C 和输出格式的文本文件
- Qt C++ 如何将加密文本的QByteArray保存到文件中,然后读取并格式化为QByteArray
- 以C++格式将数据从文本文件读取到 3D 矢量中
- 从包含 utf-8(印地语)格式文本的文件读取并写入其他文件
- 是否有用于80列格式文本输出的库/方法
- 如何读取json格式文本的字符流