Good Afternoon,

I'm reviewing structs, but don't get the concept very well.
Assume the following structure declaration is given

struct Rectangle
int length;
int width;

write a function that returns a Rectangle structure. The function should store the user's input in the members of the structure before returning.
So far I have this but it doesn't work.

int input(struct Rectangle*rect)
    int l,w, area;
    cout<<"Enter a length:";
    cout <<"enter a width:";
    area = l*w;
    return area;
6 Years
Discussion Span
Last Post by poloblue

Your code doesn't seem to match your description at all. You said the function should return a Rectangle, but the function in the code actually takes a rectangle (that it never uses) and returns an int.

Your function also calculates the area of the rectangle that the user entered which your description didn't say anything about. The calculation of the area should really happen in its own function.

PS: In C++ you don't need the struct keyword when declaring variables or parameters of a struct type.

Votes + Comments
Observant, good suggestion to separate calculation and printing
struct Rectangle
    int lenght, height, area;

And input code should be:

Rectangle* input()
    Rectangle rg;
    cout << "Length: ";
    cin >> rg.Length;
    cout << "Height: ";
    cin >> rg.Height;
    rg.area = rg.Length * rg.Height;

    return &rg;

Or should be:

int input(Rectangle *rg)
    cout << "Length: ";
    cin >> rg->length;
    cout << "Height: ";
    cin >> rg->height;

    rg->area = rg->length * rg->height;

@Fulctrum Your first input function is broken - it returns the address of a local variable.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.