user3217708
user3217708

Reputation: 45

what's wrong with array of structures?

I want to input the vertices of a triangle and find the area of the triangle. I read the vertices and tried to print it. But it's showing error. Can you help me out.I tried the following

#include <iostream>
#include <math.h>
using namespace std;
struct vertex {
    float x;
    float y;
};

struct triangle {
    vertex vertices[3];
};

int main()
{
    triangle t;
    for (int i = 0; i < 3; ++i) {
        double x, y;
        cin >> x >> y;
        vertex p = { x, y };
        cout << p;
        t.vertices[i] = p;
        // cout<<t.x;
    }
}

Upvotes: 0

Views: 81

Answers (1)

smac89
smac89

Reputation: 43078

Add this to your code:

std::ostream& operator << (std::ostream& oss, const vertex& v) {
    return oss << '(' << v.x << ',' << v.y << ')';
}

It is most likely complaining because it doesn't know how to display the struct you are trying to print.


Even though you stored it as {x, y}, the result is that p is still an object. C++ just gives you that ability to create objects using the list initialization syntax. To actually display this object is a different issue altogether because all it sees is some object for which the << operator is not defined to handle, so it throws it's virtual hands up in the air and spit out an error message.

But because we have just created a definition of that operator which handles the said object that was proving difficult, it now knows what to do when it sees a vertex object.

Hope that helps

Upvotes: 2

Related Questions