Hello guys. I'm pretty new at C++. I have to make this Shop-type of program, by using Array of Objects. Problem is i can't come with idea for 2 of the functions.
- to set price tag for each item;
- to search item by name;
I am looking to implement some ideas that could work... (LINES 56-57)
You can do a simple linear search using a for loop.
1. loop through each "item"
2. compare the item name with the input string
3. if a match is found then change the value (item.price =)
Does this help? I can go more in detail if needed.
I'll be brief and will only use pseudo code to give you some hints for you to work out
for searching for item by name
1 2 3 4 5
//get the name of item user wants to search
//a lovely for loop to scan the array itemsArray[]
//if the name user entered matches display details/index and get out of loop
//if there's no match print the required message
for setting/changing price of item
1 2 3 4
//use previous function to get a item
//if there's no price set set its price (a ctor may help you with default value)
//if the price is set then just update it... this should not be a problem
Line 26: You're trying to read into the next instance of MyItems. This is VERY UNSAFE. An instance of a class should NOT make assumptions that it is immediately followed by another instance. Yes, you set the state of the last item [n-1] to false, but consider if the items are in a non-sequential container such as a std::set or std::list. What if an instance gets copied? It's no longer in the same place.
Line 36: items is a local array that goes out of scope when showListItems() exists. items belongs in main(). Pass the array as an argument to showListItems().
Line 70: You can't search the array because it is local to showListItems(). As stated above, move the array to main and pass it to a search function. If you find the item, what are you going to do with it? Search() really should be a helper function.
Line 72: Create an updatePrice() function that is a member of your class. Prompt the user for the name of the object and the new price. Use the search function to locate the desired instance and then change the price.
Consider initializing your array from a file that contains object names and prices.
Consider using a std::vector instead of an array. Much safer.