2015-04-06 66 views
-1

我在写小游戏。 我想从.txt文件读取对象位置。 我想要写其内容的文件这样一个(从.txt)代码:如何阅读C++中的自定义格式文本文件

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 

浮子1是将要被创建的对象的X,第二个是Y,第三ž。 名称(如'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") { 

... }

}

此代码woriking但只有第一个对象(它仅创建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' - 不是字符)? 如何读取此序列的类型(以检查它是否可以是浮点型或仅字符串)?

我想知道如何以有效的方式做到这一点。

感谢

回答

3

看你的输入文件,你可能想要做像下面这样:

  • 对于每一行
    • 检查非数字字符
    • 如果找到了,开始一个新对象
    • else,解析坐标并创建一个新实例

有很多不同的方法可以做到这一点,下面大致显示了逻辑。

// Example program 
#include <iostream> 
#include <string> 
#include <fstream> 

bool contains_letter(std::string const& str) 
{ 
    // 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 
     } 
    } 

    // ... 
}