C++ Struct Part Type Problem

Hello Everyone,

Off the bat I want to say that I am just learning programming so if my code is missing basics I apologize. I was hoping that you might be able to give me an example of how you would solve this problem. I've spent the better part of a week now wracking my brain over this.

I have to answer this problem:
Assume that you have the following definition of a struct:
1.struct partsType
2.{
3.String partName;
4.Int partNum;
5.double price;
6.int quantitiesInStock;
7.};


Declare an array, inventory, of 100 components of type partsType.

Now take above struct definition above and:
1.Write a C++ code to initialize each component of inventory as follows: part name to null string, partNum to -1, price to 0.0 and quantities in quantitiesInStock to 0. .
2.Write a C++ code that uses a loop to output the data stored in inventory. Assume that the variable length indicates the number of elements in inventory.

I have developed to this point:
1.#include <iostream> //Declares IO Stream
2.using namespace std; //Declares Namespace
3.
4.for (int i = 0; i < 100; i++) //Declares Counter
5.
6. {
7.
8. inventory[i].partName = ""; //Sets partName = to part
9.
10. inventory[i].partNum = -1; //Sets partNum counter = -1
11.
12. inventory[i].price = 0.0; //Sets price = 0.0
13.
14. inventory[i].quantitiesInStock = 0; //Sets counter for quantity to zero.
15.
16. }
17. for (int i = 0; i < length; i++)
18.
19. {
20.
21. cout << inventory[i].partName << endl; //Output for Part Number
22.
23. cout << inventory[i].partNum << endl; //Output for Part Number
24.
25. cout << inventory[i].price << endl; //Output for Price
26.
27. cout << inventory[i].quantitiesInStock << endl; //Output for quantities
28.
29. }
30. system "pause";
31. return 0;


Any help you may provide is greatly appreciated!!!
Personally, I still don't get which part of the program you need help with, maybe you can specify EXACTLY where the help is needed.
[P.S] you don't need to number your code yourself, just begin with "[cod] and end with [/cod]", write "code" not cod like I wrote
Any program in C++ shall have function main. Also you incorrectly specified type names. Instead of String shall be string and instead of Int shall be int.

If your compiler supports C++ 2011 then the code could look the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

struct partsType
{
    std::string partName;
    int partNum = -1;
    double price;
    int quantitiesInStock;
};

int main()
{
    const size_t N = 100;
    partsType inventory[N] = {};
    
    for ( partsType part : inventory )
    {
        std::cout << "Name: "    << part.partName << ", number: "   << part.partNum 
                  << ", price: " << part.price    << ", quantity: " << part.quantitiesInStock
                  << std::endl;
    }
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.