How do I use an infinite amount of structs for a function's parameter?

210 views Asked by At

I'm writing a very simple OBJ exporter in C++ (for VC6, as I am writing for an old project that only compiles there.)

Right now, I'm stuck on figuring out how to use an infinite amount of structs to make a vertices position line. That may sound a bit silly, but this is my first functioning program written in C++, so I don't know the concepts very well.

I'm assuming I'm doing it wrong, as there's nothing I can find on the Internet for what I'm trying to do.

Here's my header's struct code:

struct PointList {
        float X;
        float Y;
        float Z;
    };

..and the actual OBJ export function's code:

void OBJEXP::WriteOBJ(OBJEXP::PointList Points, std::string File) // Writes an OBJ.
{
    ofstream    output(File + ".obj");

    for (int i = 0; i < sizeof(Points); i += 1)
    {
        output << "v " + to_string(Points.X) + " " + to_string(Points.Y) + " " + to_string(Points.Z) + "\n";
    }
    output.close();
    cout << "All done\n";
}

My main file (meant to test the code out, this is going to be run every time I save a file otherwise:)

OBJEXP::PointList POINTZ;

int main()
{
    POINTZ.X = 1.0f;
    POINTZ.Y = 5.5f;
    POINTZ.Z = 2.0f;
    OBJEXP::WriteOBJ(POINTZ, "testobject");
    std::cout << "Execution done\n";
}

My OBJ file looks like this:

v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000
v 1.000000 5.500000 2.000000

which obviously isn't very correct.

2

There are 2 answers

2
lobakkang On

I prefer to use vector :D

void OBJEXP::WriteOBJ(std::vector<OBJEXP::PointList> Points, std::string File) {
    ofstream output(File + ".obj");
    for (int i = 0; i < Points.size(); i += 1) {
        output << "v " + to_string(Points[i].X) + " " + to_string(Points[i].Y) + " " + to_string(Points[i].Z) + "\n";
    }
    output.close();
    cout << "All done\n";
}

main code:

OBJEXP::PointList POINTZ;
int main() {
    POINTZ.X = 1.0f;
    POINTZ.Y = 5.5f;
    POINTZ.Z = 2.0f;

    std::vector tmp;
    tmp.push_back(POINTZ);
    OBJEXP::WriteOBJ(tmp, "testobject");
}
0
Casey On

Your use of an ancient compiler not-withstanding, the format of .OBJ does not include the number of verts/uvs/normals/faces before the list.

You must read the file twice: first to count the number of verts/uvs/normals/faces that appear, then again to parse the actual values.

A modern compiler makes this trivial with the use of std::string, std::stringstream and std::vector. Using C-style strings, arrays, and FILE* would make this a nightmare.