So i want to do inventory program that uses a vector of class items in it. So far my code looks something like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Item{
private:
string month;
string name;
float volume;
float sales;
public:
void print();
void print2();
void sale();
void report();
void getdata();
void setname (string itemname){name=itemname;}
void setID(int setID){ID=setID;}
};
void Item::print(){
cout<<"Name : "<<name<<endl;
cout<<"ID : "<<ID<<endl;
}
void Item::print2(){
vector<Item>*::iterator i;
for (i=list.begin(); i !=list.end(); ++i){
i->print();
}
/*void Item::sale(){
vector<Item> }
void Item::report(){
}*/
void Item::getdata(){
vector<Item> items;
string name;
int ID;
Item *a;
for (int n=0; n<2; n++){
cout<<"Enter name:"<<endl;
getline(cin, name);
cout<<"Enter ID: "<<endl;
cin>>ID;
a = new Item;
a->setname(name);
a->setID(ID);
items.push_back(*a);
cin.get();
}
}
int main(){
cout<<"0. Exit \n1. Item Sale \n2. Daily Report \n3. Weekly Check \n4. Monthly Update \n5. Load Inventory File \n6. S\
ort file by Key \n7. Save inventory to a file \n8. Add a New Item \n9. Edit an Item \n10. Delete an item\n";
int x;
cin>>x;
switch(x){
case 0:
exit(0);
break;
case 1:
sale();
break;
case 2:
break;
case 8:
getdata();
break;
default:
cout<<"Wrong choice!\n";
break;
}
the program doesn’t compile because getdata() in case 8 doesn’t call the function, why is that? Another question is so if i have stored data in getdata() function how can i use that data vector data in other function by dereferencing?
I would recommend splitting your object design into two parts: one to represent an Item, and one to represent the Inventory.
Item:
Inventory:
.
And here’s what your main would look like:
Notice that you need an object of the class in order to call a member function.
getdata()doesn’t mean anything without the object on which it acts.Edit: You asked “how would you iterator through the vector to find specific ID for example?”
We already see how to iterate through to call print on every member. All we really need to do is only call print sometimes.
First, you need a way to tell the ID of an Item. Add this after setID(…) in Item:
Now you can check this value while iterating:
You can see a working example here: http://codepad.org/w1MwGCYo