Passing an object to a method C++ - c++

Sorry for grammar, not a native speaker.
So I've got an assignment to create a simple program where you should be able to create three people, pass in their name, country, occupation and phone number. You should be able to print out saved information as a spreadsheet.
So I came up with this kind of piece of code:
#include <iostream>
#include <iomanip>
using namespace std;
class Person {
public:
string surname;
string name;
string country;
string occupation;
string phone;
// Set default value
Person() {
surname = "empty";
name = "empty";
country = "empty";
occupation = "empty";
phone = "empty";
}
// SET PERSON'S DATA
void set_surname(string entered_surname) {
surname = entered_surname;
}
void set_name(string entered_name) {
name = entered_name;
}
void set_country(string entered_country) {
country = entered_country;
}
void set_occupation(string entered_occupation) {
occupation = entered_occupation;
}
void set_phone(string entered_phone) {
phone = entered_phone;
}
// RETURN PERSONS DATA
string get_surname() {
return surname;
}
string get_name() {
return name;
}
string get_country() {
return country;
}
string get_occupation() {
return occupation;
}
string get_phone() {
return phone;
}
};
void create_a_frankenstein(Person person) {
string entered_data;
cout << "Please, enter person's surname: \n";
cin >> entered_data;
person.set_surname(entered_data);
cout << "Please, enter person's name: \n";
cin >> entered_data;
person.set_name(entered_data);
cout << "Please, enter person's country: \n";
cin >> entered_data;
person.set_country(entered_data);
cout << "Please, enter person's occupation: \n";
cin >> entered_data;
person.set_occupation(entered_data);
cout << "Please, enter person's phone: \n";
cin >> entered_data;
person.set_phone(entered_data);
}
int main() {
Person fst;
Person snd;
Person trd;
Person group[3] = {fst, snd, trd};
int people_created = 0;
bool switch_on = true;
while (switch_on) {
cout << "What operation would you like to perform: \n";
cout << " 1) Create new person \n";
cout << " 2) Print out all of the available information \n";
cout << " 3) Quit \n";
//Get the number of operation to perform
int operation;
cout << "Please, enter a number: \n";
cin >> operation;
switch (operation) {
//Option 1: create a person
case 1:
if (people_created == 3) {
cout << "It is not possible to create more that three people";
}
else {
create_a_frankenstein(group[people_created]);
people_created++;
}
break;
//Option 2: print out all of the available information
case 2:
for (int i = 0; i < 3; i++) cout << setw(20) << setfill(' ') << left << group[i].get_surname();
for (int i = 0; i < 3; i++) cout << setw(20) << setfill(' ') << left << group[i].get_name();
for (int i = 0; i < 3; i++) cout << setw(20) << setfill(' ') << left << group[i].get_country();
for (int i = 0; i < 3; i++) cout << setw(20) << setfill(' ') << left << group[i].get_occupation();
for (int i = 0; i < 3; i++) cout << setw(20) << setfill(' ') << left << group[i].get_phone();
break;
// Option 3: quit
case 3:
switch_on = false;
break;
}
}
}
Everything seem to work just fine. Except it doesn't change information in object's variables.
My guess is that when I pass a Person-type object to create_a_frankenstein(), method creates a copy of an object and starts working with a copy without changing anything in the original object.
I've tried to use pointer. I manage to do what I intend to on simplier examples:
void first(int* a){
for (int i = 0; i < 7; i++) {
a[i] = a[i]+1;
}
}
int main() {
int a[7] = {0, 1, 2, 3, 4, 5, 6};
for (int i=0; i<7; i++) {
cout << a[i] << ' ';
}
}
But when I try to use it in the Lab, it doesn't work as easily.
Will be glad to receive any advices on how to solve the problem and what topics I should brush up or look deeper in. Thank you in advance!

Try to pass your Person objects by reference. You can find more here: passing object by reference in C++. Btw in your code example you don't call your function named 'first'.

The problem is on the void create_a_frankenstein(Person person) method.
You are passing a copy of the Person's object. If you want to keep the changes made to an object pass it as a reference: void create_a_frankenstein(Person& person)
Note:
Don't use arrays. Use std::vector instead if you want to store sequences of objects.
It would be nice if you define any getter member function as const --> return_type getter_name(params) const { //body here}

Related

program stopped working when I'm trying to input [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm working on a project, to create a linked list in class but I can't even start working on it because every time I run the program it's will stop working when I want to input data.
Can someone tell me how to input data properly using class? and if possible please let me know how to improve this program. The code that I've done is quite long.
I'll try to make it short and simple for you guys to understand. A lot of people been suggesting me to use std::string but our lecturer never mentioned about it so we have no idea how to use it.
If I have to use it that means I have to start learn it from the beginning which means it will take time for me to really understand it.
We're also required to have a function where we can update the data stored, search the data based on one of its data and make a summary for it.
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#include <conio.h>
#include <stdio.h>
#include <string>
using namespace std;
//CLASS USED IN PROGRAM
class carInsurance
{
private:
int total;
int customerNo;
string name;
string iCno;
char dob[10];
string nationality;
string address;
char phoneNo[15];
string email;
string occupation;
char carNo[10];
char expireDate[11];
float insuranceAmount;
char carUsage[30];
char manufacturingDate[11];
int package;
int option;
int additional;
int noCustomer[10];
public:
void add();
void presetdata();
static void deleteFunc(carInsurance noCustomer[]);
static void viewAll(carInsurance noCustomer[]);
//constructor name has to be the same as class
carInsurance(int carInsurance_total,
int carInsurance_customerNo,
string carInsurance_name,
string carInsurance_iCno,
char carInsurance_dob[10],
string carInsurance_nationality,
string carInsurance_address,
char carInsurance_phoneNo[15],
string carInsurance_email,
string carInsurance_occupation,
char carInsurance_carNo[10],
char carInsurance_expireDate[11],
float carInsurance_insuranceAmount,
char carInsurance_carUsage[30],
char carInsurance_manufacturingDate[11],
int carInsurance_package,
int carInsurance_option,
int carInsurance_additional)
{
total = carInsurance_total;
customerNo = carInsurance_customerNo;
name = carInsurance_name;
iCno = carInsurance_iCno;
dob[10] = carInsurance_dob[10];
nationality = carInsurance_nationality;
address = carInsurance_address;
phoneNo[15] = carInsurance_phoneNo[15];
email = carInsurance_email;
occupation = carInsurance_occupation;
carNo[10] = carInsurance_carNo[10];
expireDate[11] = carInsurance_expireDate[11];
insuranceAmount = carInsurance_insuranceAmount;
carUsage[30] = carInsurance_carUsage[30];
manufacturingDate[11] = carInsurance_manufacturingDate[11];
package = carInsurance_package;
option = carInsurance_option;
additional = carInsurance_additional;
} // end of constructor
carInsurance()
{ // Set all variables to null
total = 0;
customerNo = 0;
name = " ";
iCno = " ";
dob[10] = '\0';
nationality = " ";
address = " ";
phoneNo[15] = '\0';
email = " ";
occupation = " ";
carNo[10] = '\0';
expireDate[11] = '\0';
insuranceAmount = 0;
carUsage[30] = '\0';
manufacturingDate[11] = '\0';
package = 0;
option = 0;
additional = 0;
}
// SET
void setChar(char carInsurance_dob[10],
char carInsurance_phoneNo[15],
char carInsurance_carNo[10],
char carInsurance_expireDate[10],
char carInsurance_carUsage[30],
char carInsurance_manufacturingDate[10])
{dob[10] = carInsurance_dob[10];
phoneNo[15] = carInsurance_phoneNo[15];
carNo[10] = carInsurance_carNo[10];
expireDate[11] = carInsurance_expireDate[11];
carUsage[30] = carInsurance_carUsage[30];
manufacturingDate[11] = carInsurance_manufacturingDate[11];}
void setname(string carInsurance_name){name = carInsurance_name;}
void setiCno(string carInsurance_iCno){iCno = carInsurance_iCno;}
void setAddress(string carInsurance_address){address = carInsurance_address;}
void setString(string carInsurance_nationality, string carInsurance_email,string carInsurance_occupation)
{nationality = carInsurance_nationality; email = carInsurance_email; occupation = carInsurance_occupation;}
void setInt(int carInsurance_total, int carInsurance_customerNo, int carInsurance_package, int carInsurance_option, int carInsurance_additional)
{customerNo = carInsurance_customerNo; package = carInsurance_package; option = carInsurance_option; additional = carInsurance_additional;}
void setFloat (float carInsurance_insuranceAmount){insuranceAmount = carInsurance_insuranceAmount;}
// GET
string getname(){return name;}
string getiCno(){return iCno;}
string getaddress(){return address;}
string getString(){return nationality; return email; return occupation;}
int getInt(){return total; return customerNo; return package; return option; return additional;}
float getFloat(){return insuranceAmount;}
}; //end class
Here goes my main:
//function declaration
//to prevent overload run function outside
void add();
//THE MAIN FUNCTION OF PROGRAM
int main()
{
carInsurance obj; // obj is class object
carInsurance *noCustomer[10];
int choice;
while(choice != 4)
{
cout << "1. ADD, UPDATE, DELETE\n" << "2. SEARCH\n" << "3. VIEW ALL\n" << "4. SUMMARY REPORT\n" << "5. EXIT\n" << endl;
cout << "Enter your choice: ";
cin >> choice;
system("cls");
switch(choice)
{
case 1:
{
cout << "___________________________________\n";
cout << "\n\tADD/UPDATE/DELETE\n";
cout << "___________________________________\n";
cout << "\n1. ADD\n2. UPDATE\n3. DELETE\n" << endl;
cin >> choice;
system("cls");
switch(choice)
{
case 1:
{
int i;
int total = 0;
cout << "How many customer? ";
cin >> total;
for(i=0; i<total; ++i)
{
cout << "________________________________\n";
cout << "\n\tCUSTOMER NO. " << 1 + i;
cout << "\n________________________________\n";
noCustomer[i]->add(); // this is function call to input
}
break;
}
case 2:
{
int paymentID;
//cout << "UPDATE" << endl;
cout << "\nEnter the customer ID that you want to update:";
cin >> paymentID;
// function here
break;
}
case 3:
{
int paymentID;
//cout << "DELETE" << endl;
cout << "\nEnter the customer ID that you want to delete:";
cin >> paymentID;
noCustomer[10]->deleteFunc(noCustomer[10]);
break;
}
} // End of switch case for add,update,delete
system("cls");
break;
} // End of case 1
case 2:
{
cout << "___________________________\n";
cout << "\n\t SEARCH\n";
cout << "___________________________\n";
system("pause");
system("cls");
break;
}
case 3:
{ cout << "___________________________\n";
cout << "\n\tVIEW ALL\n";
cout << "___________________________\n";
obj.presetdata();
noCustomer[10]->viewAll(noCustomer[10]);
cout<<"\n";
system("pause");
system("cls");
break;
}
case 4:
{
cout << "___________________________\n";
cout << "\n\tSUMMARY REPORT\n";
cout << "___________________________\n\n";
cout << "1. Sorted by different month\n2. Sorted by different car type\n3. Sorted by different insurance" << endl;
cin >> choice;
switch(choice)
{
case 1:
{
break;
}
case 2:
{
break;
}
case 3:
{
break;
}
default:
cout << "Wrong input! Please choose again: ";
cin >> choice;
system("pause");
}
break;
}
case 5:{
cout << "___________________________\n";
cout << "\n\tTHANK YOU!\t\n";
cout << "___________________________";
exit(0); }
default:
continue;
}// End of switch case
}// End of while
return 0; //indicates success
}//End of main
I see a problem in the inner switch statement:
case 1:
{
int i;
int total = 0;
cout << "How many customer? ";
cin >> total;
for(i=0; i<total; ++i)
{
cout << "________________________________\n";
cout << "\n\tCUSTOMER NO. " << 1 + i;
cout << "\n________________________________\n";
noCustomer[i]->add(); // this is function call to input
break;
}
}
case 2:
The break operator breaks the loop, but does not prevent executing case 2: branch.
Yet another problem: re-assignment of choice. User may input 4 in any input request that will break while (choice != 4) unexpectedly. You can avoid troubles with break and re-assignments by using functions.
There is a lot of out of array bounds access by indexes that are equal to array sizes.
It is not clear what you want to reach in dob[10] = carInsurance_dob[10]; It copies 11th char. Maybe you want to copy the whole char array. Use std::string for error-free code.

What is a deleted function, and why only my functions that I pass files into are considered deleted? [duplicate]

This question already has answers here:
Using fstream Object as a Function Parameter
(3 answers)
Closed 6 years ago.
#include <bits/stdc++.h>
using namespace std;
class contact {
private:
vector< pair<string, int> > contact_info;
public:
void add_contact(string contact_name, int contact_number) {
contact_info.push_back(make_pair(contact_name, contact_number));
sort(contact_info.begin(),contact_info.end());
}
void edit_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
cout << "Enter the new number: ";
cin >> contact_info[found_at].second;
}
void show_all() {
for (unsigned int i =0; i < contact_info.size(); i++) {
cout << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void delete_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
for (unsigned int i =0; i < contact_info.size(); i++) {
contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void readFile(ifstream contact_file) {
string input;
while (!contact_file.eof()) {
contact_file >> input;
size_t pos = input.find(" ");
string name = input.substr(0,pos);
string number_str = input.substr(pos);
int number = stoi(number_str) ;
contact_info.push_back(make_pair(name,number));
}
}
};
int main()
{
int choice;
ifstream contacts_file_read;
contacts_file_read.open("contacts.txt");
ofstream contacts_file_write;
contacts_file_write.open("contacts.txt");
bool in_prog = true;
contact contacts;
string name;
int number;
while (in_prog) {
cout << "1. Add contacts" << endl
<< "2. Edit contact" << endl
<< "3. Delete contact" << endl
<< "4. Show all" << endl
<< "5. exit" << endl;
cout << "Your choice: ";
cin >> choice;
contacts.readFile(contacts_file_read);
if (choice == 1) {
cout << "Enter name & number separated by a space: ";
cin >> name >> number;
contacts.add_contact(name, number);
} else if (choice == 2) {
cout << "Enter name of contacts to be edited: ";
cin >> name;
contacts.edit_contact(name);
} else if (choice == 3) {
cout << "Enter name of contact to be deleted: ";
cin >> name;
contacts.delete_contact(name);
} else if (choice == 4) {
contacts.show_all();
} else if(choice == 5) {
contacts.writeFile(contacts_file_write);
} else {
cout << "Wrong choice" << endl;
}
}
return 0;
}
So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.
Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
// ^^^^^^^^^^

How to alphabetize a list on C++

I have been having some trouble on my code for my final project. I have looked everwhere and I am having a hard time so I thought I would ask on here. I need to make sure that when all the names are listed in this phonebook that they will come out in alphabetical order but as of yet I am unsure how to do that. Here is the program that i currently have! Thank you!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct Contact {
string name, number, notes;
};
Contact contactList[100];
int rec_num = 0;
int num_entries;
string toUpper (string S) {
for (int i= 0; i < S.length(); i++)
S[i] = toupper(S[i]);
return S;
}
void ReadFile () {
string S;
fstream input("PhoneData.txt");
while (!input.eof() && !input.fail()){
input >> contactList[rec_num].name >> contactList[rec_num].number;
getline(input, S);
contactList[rec_num].notes = S;
rec_num++;
}
cout << "Book read." << endl;
num_entries = rec_num;
input.close();
return;
}
// stores phonebook for future runs of the program
void StoreFile () {
fstream F ("PhoneData.txt");
rec_num = 0;
while (rec_num < num_entries){
F << contactList[rec_num].name << " " << contactList[rec_num].number << " " << contactList[rec_num].notes << " " << endl;
rec_num++;
}
cout << "Phonebook stored." << endl;
return;
}
// adds contact
void add_name(string name, string number, string notes){
contactList[num_entries].name = name;
contactList[num_entries].number = number;
contactList[num_entries].notes = notes;
num_entries++;
return;
}
// finds contact
void retrieve_name(string name){
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
cout << "Phone Number: " << contactList[i].number << endl << "Notes: " << contactList[i].notes << endl;
return;
}
}
cout << "Name not found" << endl;
return;
}
// updates contact info
void update_name(string name){
string new_number;
string new_notes;
cout<<"New Phone Number"<<endl;
cin>> new_number;
cout<<"New Notes"<<endl;
cin>> new_notes;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
contactList[i].number = new_number;
contactList[i].notes = new_notes;
return;
}
}
}
// deletes contact
void delete_name(string name){
int INDEX=0;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
INDEX=i;
for ( int j=INDEX; j < num_entries; j++ ){
contactList[j].name = contactList[j+1].name;
contactList[j].number = contactList[j+1].number;
contactList[j].notes = contactList[j+1].notes;
}
}
}
return;
}
void listAllContacts() {
int i = 0;
while (i < num_entries) {
cout << "-- " << contactList[i].name << " " << contactList[i].number << endl << "-- " << contactList[i].notes << endl << endl;
i++;
}
}
int main(){
string name, number, notes;
string FileName;
char command;
FileName = "PhoneData.txt";
ReadFile ();
cout << "Use \"e\" for enter, \"f\" for find, \"l\" for list, \"d\" for delete, \"u\" for update, \"s\" for send message, \"q\" to quit." << endl << "Command: ";
cin >> command;
while (command != 'q'){
switch (command){
case 'e': cin >> name; cout << "Enter Number: ";
cin >> number; cout << "Enter Notes: ";
cin.ignore(); getline(cin, notes);
add_name(name, number, notes); break;
case 'f': cin >> name; retrieve_name(name); break;
case 'l':
listAllContacts(); break;
case 'u': cin>> name; update_name (name);break;
case 'd' : cin>> name; delete_name (name); break;
}
cout << "\nCommand: "; cin >> command;
}
StoreFile();
cout << "All set !";
return 0;
}
Given
Contact contactList[100];
int num_entries;
you can use std::sort to sort the list of contacts. std::sort has two forms. In the first form, you can use:
std::sort(contanctList, contactList+num_entries);
if you define operator< for Contact objects.
In the second form, you can use:
std::sort(contanctList, contactList+num_entries, myCompare);
if you define myCompare to be callable object that can compare two Contact objects.
To use the first form, change Contact to:
struct Contact {
string name, number, notes;
bool operator<(Contact const& rhs) const
{
return (this->name < rhs.name);
}
};
If you want to the comparison of names to be case insensitive, convert both names to either uppercase or lowercase and them compare them.

i need to create array on the heap aby to hold a specific number set by the user

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];

Exception handling trouble, why?

Here is my main:
int main() {
Inventory Master;
bool flag;
Customer Bob("Bob", "CreditCard.txt");
Customer Joe("Joe", "CreditCard.txt" );
Master.firststock( "inventory.txt" );
vector<Food> temp = Master._Inv;
cout <<"Hi, What would you like to buy today?" << endl;
for(unsigned int i=0; i<temp.size(); i++ ) {
cout << temp[i].name << " " << temp[i].quant << " " << temp[i].price << endl;
}
cout <<"\n";
Food Apple("Apples", .99, 10);
Food Orange("Oranges", .99, 10);
Food Chip("Chips", 3.00, 10);
cout <<"\nHi Bob" << endl;
flag = Bob.addCart(Apple, 7, &Master);
cout <<"Bob's total purchases are Currently: \n";
Bob.report();
flag = Bob.addCart(Orange, 2, &Master);
flag = Bob.addCart(Chip, 2, &Master);
Bob.report();
flag = Bob.removeCart();
Bob.report();
cout <<"Bob, ";
flag = Bob.checkout(&Master);
here is the following i implemented to remove food from my vector _Cart:
bool Customer::removeCart() {
bool flag;
int q = 0;
unsigned int i=0;
string remove;
cout << "\nWhat would you like to remove and how much would you like to remove?" << endl;
cin >> remove >> q;
for (i =0; i < _Cart.size(); i++) {
if(remove == _Cart[i].name) {
if (q >= 0) {
_Cart[i].quant -= q;
//inv->_Inv[i].quant += q;
cout <<"\nYou removed " << q << " " << remove <<" In your cart\n" << endl;
return true;
}
if (q < 0) {
cout << "Invalid number of " << remove << " being removed.\n" << endl;
return true;
}
}
else {
try {
throw remove;
}
catch (string param) {
cout << "\n" << remove << " doesn't exist in your cart\n" << endl;
}
return true;
}
}
My header containing the the function removeCart:
class Customer {
public:
Customer(string n, string fileName);
~Customer() { _Cart.clear(); };
bool addCart(Food f, int q, Inventory* inv);
bool removeCart();
void report();
bool checkout(Inventory* inv);
protected:
string remove;
string name;
int q;
int card;
double balance;
CreditCard _CC(int card,double balance);
vector<Food> _Cart;
};
Now for some reason when i call removeCart, entering "Apples" works but i noticed i made a food object called Apple so not sure why typing "Apples" works for being removed instead of "Apple". Also when i try "Orange" or "Chip" the exception is shown but as you can see in main i added Chip and Orange to Bob's Cart. I could appreciate the help.
You are making an object called Apple containing a member of type std::string which holds characters "Apples". Only your compiler knows that you called an object Apple but your program compare string "Apples" with your input. Same with Orange and Chip.
You've declared an object called Apple somewhere in your code.
You've then instantiated an instance of an Apple class and set the Apple::name member to 'Apples', a string.
You're not comparing the input with the class name, you're comparing the input with the member data of the Apple class.