0

I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)

And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.

So far I have:

#include <iostream>
#include <string>

using namespace std; 
void display();

struct part_rec
{
  int part_num;
  string part_name;
  int part_quantity;
  double part_cost;
};

int main()
{
   part_rec Robot_parts[ ] = {
                              {7789, "QTI", 4, 12.95},
                              {1654, "bolt", 4, 0.34},
                              {6931, "nut", 4, 0.25} 
                                                    };
return 0;
}

void display()
{
    cout<<Robot_parts[]<<endl<<endl;
}

If I also made a few other errors, please let me know. Thanks!

1 Answers1

0

As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.

But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:

#include <iostream>
#include <string>
#include <vector>

using namespace std; 
struct part_rec
{
    int part_num;
    string part_name;
    int part_quantity;
    double part_cost;
};

// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);


// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to @BaumMitAugen who provided this comment and link:
//       It makes use of the so called Operator Overloading - see:
//       https://stackoverflow.com/questions/4421706/operator-overloading
//       The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m) 
{ 
    // Note - Only two members printed here - just add the rest your self
    return os << m.part_num << " " << m.part_name;
}


int main()
{
     part_rec Robot_parts[] {
                              {7789, "QTI", 4, 12.95},
                              {1654, "bolt", 4, 0.34},
                              {6931, "nut", 4, 0.25} 
                            };
     display(Robot_parts, 3);
     return 0;
}

void display(part_rec* Robot_parts, int n)
{
    // Loop over all instances of your class in the array
    for (int i = 0; i < n; ++i)
    {
        // Print your class
        cout << Robot_parts[i] << endl;
    }
}

The link recommended by @BaumMitAugen: Operator overloading

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • 1
    For the beginners who read this answer: It makes use of the so called [Operator Overloading](https://stackoverflow.com/questions/4421706/operator-overloading) (recommended read). – Baum mit Augen Apr 17 '16 at 21:32