如何在C++中读取自定义格式的文本文件

How to read custom format text file in C++

本文关键字:格式 文本 文件 自定义 读取 C++      更新时间:2023-10-16

我正在写小游戏。我想从.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
        }
    }
    
    // ...
}