【问题标题】:Read file with pattern in C++在 C++ 中读取带有模式的文件
【发布时间】:2015-02-12 12:22:22
【问题描述】:

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

我要读取的文件是这样的:

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();

    }

【问题讨论】:

  • 首先尝试找到一个现有的库来读取和解析您拥有的文件格式。如果没有(值得怀疑,除非您自己编写文件格式,或者这是用于例如大学作业),那么您可能需要阅读有关解析和/或状态机的信息。

标签: c++ file getline


【解决方案1】:

使用输入运算符:

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类等编写构造函数, 这将使代码更清晰。

【讨论】:

  • 这对我有用。谢谢!但是对象的名称是未知的,所以我检查了 noun == "object",但是我怎样才能重复这个而不是对象呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
相关资源
最近更新 更多