I have "items" in an "inventory" array, the inventory array is a struct composed of several different parts however I want to be able to search for a certain part of the array by using the item name alone (so I can make functions to delete, purchase, etc.) I was wondering how I would go about doing so and if it would instead be easier to convert the struct to a class instead if need be. Keep in mind a good amount of it is still a work in progress, I'm specifically aiming for the removeItem function currently however. Thanks in advance for any and all help!
my code is here:
#include "integerstore.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void removeItem(Item);
int buyItem(Item, int);
int sellItem(Item, int);
void stockReport(Item);
struct Item
{
string name;
float cost;
float price;
int quantity;
};
int main()
{
Item inventory[100];
int total = 0;
string cmd;
cout << "Welcome to inventory management. To add a new inventory item type add, to remove and item from inventory type remove, to add to inventory quantity type buy, to mark a sold item type sell, to see the current inventory report type report and to end the program type stop" << endl;
do
{
cin >> cmd;
if (cmd == "add")
{
cout << "Enter the new item's name";
cin >> inventory[i].name;
cout << endl;
cout << "Enter the new item's cost";
cin >> inventory[i].cost;
if (inventory[i].cost <= 100.00)
{
break;
}
else
{
cout << "Cost of item may not exceed 100.00, please reenter.";
cin.clear();
}
cout << endl;
cout << "Enter the new item's selling price";
cin >> inventory[i].price;
if (inventory[i].price <= 100.00)
{
break;
}
else
{
cout << "Selling price may not exceed 100.00, please reenter.";
cin.clear();
}
cout << endl;
i++;
}
else if (cmd == "remove")
removeItem(inventory[100]);
else if (cmd == "buy")
buyItem(inventory[100], total);
else if (cmd == "sell")
sellItem(inventory[100]);
else if (cmd == "report")
stockReport(inventory[100]);
else if (cmd != "stop")
cout << "invalid";
}
while (cmd != "stop");
system ("pause");
return 0;
}
int buyItem(Item w, int w2)
{
string itemName;
cout << "Enter the item name of which you wish to add more stock to" << endl;
cin >> itemName;
}
int sellItem(Item x, int x2)
{
}
void removeItem (Item y)
{
string itemName;
cout << "Enter the item name you wish to remove from the inventory" << endl;
cin >> itemName;
}
void stockReport(Item z)
{
}
You can use a map<string, Item> (you might want to remove name from the Item struct).
Then you can use it for instance like this:
map<string, Item> inventory;
// Add
inventory["stuff"].cost = 12;
// ...
// Get
string name;
cin >> name;
Item myItem = inventory[name];
Related
I am not sure how to connect a part of an array or if it is even possible.
My code is as follows:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string name;
string date[3];
double height[3];
double enter;
cout << "Enter name of a pole vaulter: ";
cin >> name;
cout << "Enter date of first vault: ";
cin >> date[0];
cout << "Enter height of first vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[0] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of second vault: ";
cin >> date[1];
cout << "Enter height of second vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[1] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of third vault: ";
cin >> date[2];
cout << "Enter height of third vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[2] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
int len = sizeof(height) / sizeof(height[0]);
sort(height, height + len, greater<int>());
cout << "Stats for " << name << ":" << endl;
for (int i = 0; i < len; i++) {
cout << height[i] << " ";
}
cout << height[0];
}
I am trying to enter dates and a double value, and then organize the double values in descending order and keep the dates with the corresponding value. I am not sure if this is possible, any alternative way of completing this would be helpful.
Thank you
Group of data, data sorting, multiple data points that should be aligned/connected to their respective other data points. I think the best solution here would be the use of a struct or class with vectors:
Let's say you want a variable that contains both your date and number. We can construct a class or structure for that:
#include <iostream>
using namespace std;
struct str1
{
string date;
double number;
};
class cls1
{
public:
string date;
double number;
};
int main()
{
str1 ob1;
cls1 ob2;
ob1.date = "somedate";
ob1.number = 12345;
cin >> ob1.date;
cout << ob1.date << " " << ob1.number << endl;
ob2.date = "somedate2";
ob2.number = 54321;
cin >> ob2.number;
cout << ob2.date << " " << ob2.number << endl;
return 0;
}
Having a class or struct enables you to use objects (variables made from those structs or classes). Every object created has their own place in memory for storing both date and number. You can use, find, search any of these variables and have access to both values this way.
Grouping them up so there's a list of them can be done in vectors.
Vectors are like better arrays. They not only have a dynamical size (meaning its size can change and doesnt stay static like in arrays), but they also have quite a bit ready made functions for you to use:
bool sortingFunction(int &a, int &b)
{
if (a > b) return true;
else return false;
}
int main2()
{
vector<int> numbers;
//to add
numbers.emplace_back(5); //5 is the number to add
//to remove
numbers.erase(numbers.begin() + 2); //2 is the index of the variable to delete
//to sort
sort(numbers.begin(), numbers.end(), sortingFunction);
return 0;
}
Vectors need the #include <vector> header.
Sort is a function that sorts. Needs #include <algorithm> header.
Sort function is neat because you can define the logic behind how you want to sort the vector or array with a seperate function that returns either true or false.
For your example you could do something like this in the end:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myType
{
string date;
double number;
};
bool sortByDate(myType &a, myType &b)
{
if (a.date > b.date) return true;
else return false;
}
bool sortByNumber(myType &a, myType &b)
{
if (a.number > b.number) return true;
else return false;
}
int main()
{
vector<myType> variables;
int num;
cout << "how many do you want to add" << endl;
cin >> num;
for(int i = 0; i < num; i++)
{
myType tmp;
cout << "Enter date of var" << i+1 << ": ";
cin >> tmp.date;
cout << "Enter number of var" << i+1 << ": ";
cin >> tmp.number;
variables.emplace_back(tmp);
}
//after that you can use the vector as you want...
//sort
sort(variables.begin(), variables.end(), sortByDate);
sort(variables.begin(), variables.end(), sortByNumber);
//delete
variables.erase(variables.begin()+5);
//or clear the entire thing
variables.clear();
//Either way each item in the vector consists of both number and date thus even
//if you sort the vector the values are still connected at the same position
return 0;
}
I am trying to make a basket system for a C++ program, and I am stuck with the task of obtaining the price from one vector in a separate class, and copying that price into the new "Basket" Vector. i have tried a number of workaround but I have gotten as far as having it return the error message that the identifier is undefined, even though the vector is public in the class.
the header file :
class Item {
private:
int _ItemNo;
string _category, _description;
double _price;
double _VAT = _price*0.2;
double _subtotal = _price + _VAT;
};
class ItemMenu {
public:
vector<Item> _Items;
ItemMenu();
void displayMenu();
};
//Class for ordering from the menu
class Ordering {
private:
vector<Item> _Basket;
int quantity;
double total;
public:
Ordering();
Ordering(int quantity, double total);
void placeOrder(const vector<Item> &Items);
The implementation file:
ItemMenu::ItemMenu() {
ifstream fin("Menu.txt");
if(fin) {
while(!fin.eof()) {
string _ItemNoTemp;
getline(fin, _ItemNoTemp, ':');
int _ItemNo = stoi(_ItemNoTemp);
string _category;
getline(fin, _category, ':');
string _description;
getline(fin, _description, ':');
string _priceTemp;
getline(fin, _priceTemp);
double _price = stod(_priceTemp);
if(!fin.eof()) {
_Items.push_back(Item(_ItemNo,
_category, _description, _price));
};
fin.peek();
}
fin.close();
}
}
//Method to display the each item
void ItemMenu::displayMenu() {
for(int i = 0; i < _Items.size(); ++i) {
_Items[i].display();
}
cout << endl;
}
Ordering::Ordering() { }
void Ordering::placeOrder() {
int select;
cout << "Please enter an item number: ";
cin >> select;
Item I;
i._subtotal = _Items[select]._subtotal;
_Basket.push_back(i);
}
It is in the ordering class that the basket vector is in, and I am trying to get the subtotal for the items, so that I may calculate the total by summing the values in the vector. This is also where the error saying that _Items is undefined appeared. I am new to programing and haven't really been able to find a clear source for how vectors work between classes depending on where they are declared.
Something like this should work
void Ordering::placeOrder(
const vector<Item>& items ) {
int select;
cout << "Please enter an item number: ";
cin >> select;
cItem i;
i._price = items[ select ]._price;
_Basket.push_back( i );
}
You don't actually pass an ItemMenu object to this function. That's why you are getting an undefined error.
Instead of this
void Ordering::placeOrder() {
int select;
cout << "Please enter an item number: ";
cin >> select;
_Basket.push_back(_Items[select]._subtotal);
}
You would want to do this
void Ordering::placeOrder(ItemMenu yourItemMenuVarible) {
int select;
cout << "Please enter an item number: ";
cin >> select;
_Basket.push_back(_Items[select]._subtotal);
}
then when you call it you would pass it the ItemMenu variable you defined and I think that should fix it.
I would also recommend you not have variables like the vector public, it not a very good practice for security reasons. Learning good habits now will help you in the future. The idea of keeping them private is called Encapsulation here are some sources on the topic
https://www.geeksforgeeks.org/encapsulation-in-c/
https://www.tutorialspoint.com/cplusplus/cpp_data_encapsulation.htm#:~:text=Encapsulation%20is%20an%20Object%20Oriented,from%20outside%20interference%20and%20misuse.&text=This%20means%20that%20they%20can,other%20part%20of%20your%20program.
Thanks for all the help guys i ended up fixing it with your help the code is below.
Header File:
class Ordering {
private:
vector<Item> _Basket;
int quantity;
double total;
public:
Ordering();
Ordering(int quantity, double total);
void placeOrder(vector<Item> Items);
};
Implementation:
Ordering::Ordering() { }
void Ordering::placeOrder(vector<Item> _Items) {
int select;
Item i;
char cont;
do{
cout << "Please enter an item number: ";
cin >> select;
i._ItemNo = _Items[select-1]._ItemNo;
i._description = _Items[select-1]._description;
i._subtotal = _Items[select-1]._subtotal;
_Basket.push_back(i);
cout << i._subtotal;
cout << "Do you want to add another Item? (y/n): ";
cin >> cont;
}while(cont == 'y' || cont == 'Y');
for (int i; i < _Basket.size(); i++) {
cout << _Basket[i]._ItemNo << ':' << _Basket[i]._description
<< ':' << char(156) << _Basket[i]._subtotal << endl;
};
}
Main:
int main() {
cout << "--------------------------------" << endl;
cout << "Billing Program" << endl <<
"--------------------------------" << endl;
Ordering start;
ItemMenu display;
display.displayMenu();
start.placeOrder(display._Items);
}
I'm a beginner at coding in C++ and every other language. The problem I'm having here is in main() with the first (else if) where (UserInput == sell). I would like the function to print the data stored in the object #listPos to retrieve the cost and input it into my incomplete Profit() function, but every time I dereference the pointer (Search) I get an error code. There's something I'm missing big time please help!!
Ive already tried (*search) but there's a huge error code.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class UnSold{
public:
UnSold(string NameOfShoe, int PurchasePrice ){
name = NameOfShoe;
cost = PurchasePrice;
return;
}
void SetName(string NameOfShoe){
name = NameOfShoe;
return;
}
void SetCost(int PurchasePrice){
cost = PurchasePrice;
return;
}
string GetName() const {
return name;
}
int GetCost() const{
return cost;
}
void Profit();
void PrintItem();
private:
string name;
int cost;
};
void UnSold::Profit(){
static int profit = 0;
//profit += (sold-cost);
}
void UnSold::PrintItem(){
cout << "Name: " << this->name << " Cost: " << this->cost << endl;
}
void PrintEverything(vector<UnSold*> AllItems) {
unsigned int i;
for (i=0; i<AllItems.size(); ++i) {
cout<< i+1 << " ";
(*AllItems.at(i)).PrintItem();
}
}
int main(){
vector<UnSold*> Inventory;
string Name;
int Cost;
string UserInput;
unsigned int listPos;
UnSold* newItem = nullptr;
UnSold* search = nullptr;
while ( UserInput != "quit") {
cout << "Do you want to add, sell, print or quit?" <<endl;
cin >> UserInput;
if ( UserInput == "add") {
cout << "Enter item name: "<<endl;
cin >> Name;
cout << "Enter item cost: " << endl;
cin >> Cost;
newItem = new UnSold(Name, Cost);
Inventory.push_back(newItem);
}
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
}
else{
cout << "Error"<<endl;
}
}
else if ( UserInput == "print") {
PrintEverything(Inventory);
}
else if ( UserInput != "quit"){
}
}
return 0;
}
This is a compile error.
Remove line 85: newItem.at(listPos - 1); and it runs just fine in visual studio.
The issue is that newItem is a pointer to an element. I assume you meant to use Inventory here instead. However, that logic was already done on the previous line.
On a side note, I stongly advise against storing owning pointers like this. There's no good reason in this case not to just use vector<UnSold> instead.
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
Here you mix the use of listPos and listPos - 1.
If you're allowing the user to input position 0 indexed, then
Inventory.at(listPos-1) should be Inventory.at(listPos) and
Inventory.erase(Inventory.begin() + (listPos -1)) should be Inventory.erase(Inventory.begin() + (listPos)).
If you're letting them input the position with the indexing starting at 1, then
if (listPos < Inventory.size()) should be
if(listPos <= Inventory.size() && listPos > 0)
I have written my code for an employee management system that stores Employee class objects into a vector, I am getting no errors until I try and compile, I am getting the error: C2679 binary '==': no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion). But I am not sure why any help would be great, Thank you!
// Employee Management System
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Employee
{
public:
Employee();
string GetName();
string GetStatus();
float GetSalary();
int GetAge();
int GetYearHired();
private:
string m_Name;
string m_Status;
float m_Salary;
int m_Age;
int m_YearHired;
};
Employee::Employee()
{
m_Salary = 0;
m_Age = 0;
m_YearHired = 0;
}
string Employee::GetName()
{
string fName;
string lName;
cout << "Please enter the new employee's first name: ";
cin >> fName;
cout << "Please enter the new employee's last name: ";
cin >> lName;
m_Name = fName + lName;
return m_Name;
}
string Employee::GetStatus()
{
string status;
cout
<< "Please enter the employee's status (full time, part time, or manager): ";
cin >> status;
return m_Status;
}
float Employee::GetSalary()
{
float salary;
cout << "Please enter the employee's salary: ";
cin >> salary;
return m_Salary;
}
int Employee::GetAge()
{
int age;
while (true)
{
cout << "Please enter the employee's age: ";
cin >> age;
if (age > 0)
break;
else
cout << "Error: Please enter a positive value.";
}
return m_Age;
}
int Employee::GetYearHired()
{
int yearHired;
cout << "Please enter what year the employee was hired: ";
cin >> yearHired;
return m_YearHired;
}
class Staff
{
vector<Employee*> emps;
vector<Employee*>::const_iterator iter;
public:
Staff();
virtual ~Staff();
void Add();
void Remove();
void Clear();
void Display();
};
Staff::Staff()
{
emps.reserve(20);
}
Staff::~Staff()
{
Clear();
}
void Staff::Add()
{
Employee* emp = new Employee;
emp->GetName();
emp->GetStatus();
emp->GetSalary();
emp->GetAge();
emp->GetYearHired();
emps.push_back(emp);
}
void Staff::Remove()
{
Employee* emp;
cout << "Which employee would you like to remove?";
emp->GetName();
iter = find(emps.begin(), emps.end(), emp->GetName()); // Trying to find the employee in the datbase.
if (iter != emps.end()) // If the employee is found in the vector it is removed.
{
cout << "\n" << *iter << " was removed\n\n";
emps.erase(iter); // removes employee from the vector.
}
else // If the employee is not found in the vector, it tells the user that the employee was not found.
{
cout << "Employee not found, please choose anoter employee.\n\n";
}
}
void Staff::Clear()
{
cout << "\nDo you really want to clear all employees? (yes/no)\n"; // Asking the user if they want to clear the database.
string response;
// Storing the response of the user.
cin >> response; // Getting the users response (yes/no).
if (response == "yes") // If response is yes.
{
vector<Employee*>::iterator iter = emps.begin(); // Declares an iterator for the emps vector and sets it to the beginning of the vector.
for (iter = emps.begin(); iter != emps.end(); ++iter) // Iterates through vector.
{
delete *iter; // Deletes the iterators in the vector, freeing all memory on the heap.* iter = 0;
// Sets iterator to zero so it does not become a dangling pointer.
}
emps.clear(); // Clear vector of pointers.
}
else // If response is no.
{
cout << "\nAll employee's remain in the database.\n";
}
}
void Staff::Display()
{
Employee* emp;
if (emps.size() == 0) // Checking to see if the database is empty.
cout
<< "\nThere are no employee's in the database, add employee's to view them here.\n ";
else // If the cart contains any items.
{
cout << "\nThe database contains: \n";
for (iter = emps.begin(); iter != emps.end(); ++iter) // Displaying the inventory.
{
cout << "-------------------------------------------------";
cout << "Employee's Name : " << emp->GetName() << endl;
cout << "Employee's Status : " << emp->GetStatus() << endl;
cout << "Employee's Salary : " << emp->GetSalary() << endl;
cout << "Employee's Age : " << emp->GetAge() << endl;
cout << "Year employee was hired : " << emp->GetYearHired() << endl;
cout << "-------------------------------------------------";
}
}
}
int main()
{
int option = 0;
Staff stf;
// Welcoming the user to the Employee Management System program.
cout
<< "Welcome to our Employee Management System! To get started see the menu options below :\n ";
// Main loop
while (option != 5) // The loop will repeat until the user enters 5 as the option.
{
cout << "------------------------------------------------------------------------------------- - ";
cout << "\nMenu Options: \n";
cout << "\nTo select an option, please type in the number that corresponds to that option.\n ";
cout << "1 - Add an Employee\n2 - Remove an Employee\n3 - Clear the database\n4 - Display Employee's in Database\n5 - Quit" << endl;
cout << "\nWhat would you like to do? ";
cout << "------------------------------------------------------------------------------------- - ";
// Start of the validity check.
bool validInput = false;
while (!validInput) // The loop will repeat until the users input is valid.
{
cin >> option; // User inputs first option choice.
validInput = true; // Assign the input as valid.
if (cin.fail()) // Tests to make sure the value assigned is valid for the variable type.
{
cout << "\nPlease choose a menu option by number\n";
cin.clear(); // Clears stream error.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Removes an invalid characters.
validInput = false; // Sets the input back to false, repeats the loop.
}
}
switch (option)
{
case 1:
{
stf.Add();
break;
}
case 2:
{
stf.Remove();
break;
}
case 3:
{
stf.Clear();
break;
}
case 4:
{
stf.Display();
break;
}
case 5: // If option = 5.
cout << "\nThank you for using the Employee Management Program!\n";
// Thanks the user for using the Employee Management program.
break;
default: // If the user does not put in a valid option, it tells them to try again.
cout << "\nThat's not a valid option. Please try again.\n";
break;
}
}
system("pause");
return 0;
}
Problem
std::find is going to compare the Employee *s in emps against the std::string that is returned by GetName. There is no comparison operator defined for Employee * that does this. We can make one, but because the behaviour of GetName is to Get and name for the user, not simply return the Employee's name this will quickly become a mess.
Solution
First Stop storing pointers to Employees in the vectors. This simple change will eliminate the vast majority of your past, present and future pain. In general, use new as little as possible (Why should C++ programmers minimize use of 'new'?) and when you do find yourself needing new, prefer a smart pointer.
vector<Employee*> emps;
becomes
vector<Employee> emps;
that has a ripple effect through your code, not the least of which is
void Staff::Add()
{
Employee* emp = new Employee;
emp->GetName();
emp->GetStatus();
emp->GetSalary();
emp->GetAge();
emp->GetYearHired();
emps.push_back(emp);
}
must become
void Staff::Add()
{
Employee emp;
emp.GetName();
emp.GetStatus();
emp.GetSalary();
emp.GetAge();
emp.GetYearHired();
emps.push_back(emp);
}
But also look into emplace_back and strongly consider getting the user input and then constructing emp around it.
bool operator==(const Employee & rhs) const
{
return m_Name == rhs.m_Name;
}
or a friend function
bool operator==(const Employee & lhs,
const Employee & rhs)
{
return lhs.m_Name == rhs.m_Name;
}
and then change the call to find to compare Employees
iter = find(emps.begin(), emps.end(), emp); // Trying to find the employee in the datbase.
This may lead to more problems because iter is a const_iterator and a member variable (Rubber Ducky wants a word with you about this). Also completely ignores the fact that there are a few dozen more logical mistakes in the the code.
It seems to me (EDIT: had a commented out) string response; declaration before
cin >> response; // Getting the users response (yes/no).
Hope this points you in the right direction
EDIT:
It's there but it's commented out. Try:
cout << "\nDo you really want to clear all employees? (yes/no)\n";
// Asking the user if they want to clear the database.
string response;
// Storing the response of the user.
cin >> response; // Getting the users response (yes/no).
if (response == "yes") // If response is yes.
And I'd double check all the code to avoid the comments interfering with the code
hey guys new to this site looking some help for my final project i having to create a project that takes car data saves it to the heap and has a bunch of error checking not all the way done but getting there. but i cant grasp the heap and how to input it correctly into my code here is what i have. and it has to be under 175 lines and i still have to have it ask user if they want to write to a new file or existing. thanks ahead once again question is how do i create array on the heap able to hold the number of vech specified buy user.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class carData4
{
public:
void setYear(int& year);
void setMake(string make);
void setModel(string);
void setMileage(int& mileage);
void setName(string name);
void setNumber(string number);
int getYear(){ return itsYear; }
string getMake(){ return itsMake; }
string getModel(){ return itsModel; }
int getMileage(){ return itsMileage; }
string getName(){ return itsName; }
string getNumber(){ return itsNumber; }
private:;
int itsYear;
string itsMake;
string itsModel;
int itsMileage;
string itsName;
string itsNumber;
};
void carData4::setYear(int & year)
{
do
{
cout << "Enter the cars Year from 1910 and 2014:\n ";
cin >> year;
itsYear = year;
if (year < 1910 || year > 2014)
cout << "INVALID! please enter a correct year! ";
} while (year < 1910 || year > 2014);
}
void carData4::setMake(string make)
{
cout << "Enter the cars make:\n\n";
cin >> make;
itsMake = make;
}
void carData4::setModel(string model)
{
cout << "Enter the cars model:\n\n";
cin >> model;
itsModel = model;
}
void carData4::setMileage(int & mileage)
{
do{
cout << "Enter the cars mileage:\n\n";
cin >> mileage;
itsMileage = mileage;
}
while (mileage <0 || mileage >10000000);
cout << "NOPE enter within 0 and million miles.\n\n";
cin >> mileage;
itsMileage = mileage;
}
void carData4::setName(string name)
{
cout << "Enter your name :";
cin >> name;
itsName = name;
}
void carData4::setNumber(string number)
{
cout << "Enter Your phone number (XXX)XXX-XXXX:";
cin >> number;
itsNumber = number;
}
int main()
{
carData4 car1;
int year, mileage, numCars, ;
string make, model, name, number;
cout << "How many vehicles are to be added to inventory?.\n\n";
cin >> numCars;
for (int i = 1; i < numCars; i++){
car1.setYear(year);
car1.setMake(make);
car1.setModel(model);
car1.setMileage(mileage);
car1.setName(name);
car1.setNumber(number);
cout << car1.getYear() << "\t" << car1.getMake() << "\t " << car1.getModel()
<< "\t" << car1.getMileage() << "\t " << car1.getName() << "\t " << car1.getNumber() << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
i add some is this correct????????????????
int main()
{
carData4 car1; // *car1=new carData4[numCars];
int year,mileage,numCars;
double *cars;
string make,model,name,number;
cout << "How many vehicles are to be added to inventory?.\n\n";
cin >>numCars;
cars = new double [numCars];
for (int i=1; i<numCars;i++){
car1.setYear(year);
car1.setMake(make);
car1.setModel(model);
car1.setMileage(mileage);
car1.setName(name);
car1.setNumber(number);
cout << car1.getYear() << "\t" << car1.getMake() << "\t " << car1.getModel()
<< "\t" << car1.getMileage() << "\t " << car1.getName() << "\t " << car1.getNumber() <<endl;
delete [] cars;
}
system("PAUSE");
return EXIT_SUCCESS;
}
The best way to have dynamic storage for your use case would be to use a vector, like so:
std::cout << "How many vehicles are to be added to inventory?.\n\n";
std::size_t n;
std::cin >> n;
std::vector<carData4> cars ( n );
//gives you:
//cars[0] ... cars[ n-1 ]
http://en.cppreference.com/w/cpp/container/vector
To dynamically allocate an array based on user input:
unsigned int array_capacity;
cout << "Enter array capacity: ";
cin >> array_capacity;
int * my_array = new int[array_capacity];
Remember to delete the array using delete [] my_array;.
Edit 1: using Car class
CarData4 * my_cars = new CarData4[numCars];