使用C ++中的模式读取文件

时间:2015-02-12 12:22:22

标签: c++ file getline

我想读取一个有模式的文件,我想在最后保存这些值。例如。如果它是一个房间,它有三个值大小值,必须保存等等。

我想要阅读的文件如下所示:

room
{
    size 5 3.3 6
    wallpaper
    {
        texture flower.bmp
        tiling 3 1
    }
}
object vase
{
    translation 0.2 0 0.5
    roation 0 1 0 0
    scaling 1 1 1
    model vase.obj
    parent tisch
}
Object tisch
{
    translation 2.0 0 3
    roation 0 1 0 45
    scaling 1.5 1 1
    model tisch.obj
    parent NULL
}

我是这样开始的。如何阅读和保存房间和物体的下一行?

fstream osh("/Users/torhoehn/Desktop/room.osh", ios::in);
    string line;

    if (osh.good()) {
        while (getline(osh, line, '\0')) {
            if (line.compare("room")) {
                cout << "Found room" << endl;

            }

            if (line.compare("object")) {
                cout << "Found object" << endl;
            }
        }
        osh.close();

    }

1 个答案:

答案 0 :(得分:0)

使用输入操作符:

string noun, junk;

while(osh >> noun) {
  if (noun == "room") {
    cout << "Found room ";
    osh >> junk >> junk;  // for the brace and "size"
    float length, width, height;
    osh >> length >> width >> height;
    cout << length << " long and " << breadth << " wide" << endl;
    ...
  }

  if ( noun == "object" ) {
    osh >> noun;            // what kind of object?
    if ( noun == "vase" ) {
      cout << "found vase ";
      osh >> junk >> junk;
      float translationX, translationY, translationZ;
      osh >> translationX >> translationY >> translationZ;
      ...
    }
    if ( noun == "tisch" ) {
      cout << "found tisch ";
      osh >> junk >> junk;
      float translationX, translationY, translationZ;
      osh >> translationX >> translationY >> translationZ;
      ...
    }
    ...
  }     // object
  ...

在完美地运行之后,您可以考虑为Room类,Vase类编写构造函数,等等, 这将使代码更清晰。