Search code examples
c++filegetline

Read file with pattern in C++


I want to read a file that has a pattern and I want to save the values at the end. E.g. if it's a room it has three values size values that have to be saved and so on.

The file I want to read looks like this:

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
}

I started this way. How can I read and save the next lines for room and object?

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

    }

Solution

  • Use the input operator:

    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
      ...
    

    After you have that working perfectly, you can consider writing constructors for the Room class, the Vase class, and so on, which will make the code much cleaner.