C++ Beginner Logic Error - Returning 0 - c++

I don't understand why my code is not calculating the birthrate and the deathrate. I keep on getting 0 for both. I included the static_cast<double> to ensure this wouldn't happen. Any feedback / help?
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
int getBirths()
{
return birthrate;
}
int getDeaths()
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
void calculateBirthRate(PopInfo);
void calculateDeathRate(PopInfo);
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
void PopInfo::calculateBirthRate(PopInfo newCity)
{
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}

You accidentally made birthrate and deathrate as local variables. Remove the leading keyword double, to make it:
void PopInfo::calculateBirthRate(PopInfo newCity)
{
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
Even so, it's kind of strange that you're passing newCity by value – did you mean to store the rates back in the same object, as in:
void PopInfo::calculateBirthRate(PopInfo& newCity)
{
newCity.birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo& newCity)
{
newCity.deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
or did you mean to operate on the object in-place, as in:
void PopInfo::calculateBirthRate()
{
birthrate = static_cast<double>(bir) / citpop;
}
void PopInfo::calculateDeathRate()
{
deathrate = static_cast<double>(dea) / citpop;
}

I don't think you ever call the functions that calculate birth rate and death rate! That is on top of the issues already identified, but I'm pretty sure it matters... Put a cout debug statement in there and see if I'm right...
Another problem: since "rate" is a number between zero and 1, and your function getBirths returns an int, you are going to run into a rounding problem...
Also not sure you ever set dea and bir in the context of the class (you declare them at the main level). So many places where you are inviting problems...
The easiest solution would be to rewrite these two functions:
double getBirths()
{
return (double)numberOfBirths/citypop;
}
double getDeaths()
{
return (double)numberOfDeaths/citypop;
}
But read your code, and ask yourself what the scope of your variables is, where they are set (and if you ever set them...), where they are used, where you perform type conversions.... You can learn a lot from that.
EDIT
I couldn't help myself, and decided to copy your program and debug it. After a few simplifications in the structure I came up with the following (note I moved the two functions calculateBirthRate and calculateDeathRate inside the class definition for consistency; and I used the "internally known" variables totalCityPopulation etc, rather than some of the "alternative" ones you were using... it was getting very confusing. Finally, as I mentioned in the original answer - I made sure the birth and death rates were actually calculated. I have marked changed lines with //*** :
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
double getBirths() //*** was int
{
return birthrate;
}
double getDeaths() //*** was int
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
//*** this function moved into the class definition
void calculateBirthRate()
{
birthrate = (double)numberOfBirths/totalCityPopulation; //*** using different variables
}
//*** this function moved into the class definition
void calculateDeathRate()
{
deathrate = (double)numberOfDeaths / totalCityPopulation; //*** using different variables
}
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
newCity.calculateBirthRate(); //*** added, or it's never calculated
newCity.calculateDeathRate(); //*** added, or it's never calculated
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
When I run this code, I get the following:
What is the city name?:
Amsterdam
What is the total city population?:
1234567
What are the number of births?:
12345
What are the number of deaths?:
54321
The city name is Amsterdam
The total city population is 1234567
The birth rate is 0.00999946
The death rate is 0.044
The diff between your code and mine is:
33c33
< double getBirths()
---
> int getBirths()
38c38
< double getDeaths()
---
> int getDeaths()
68,71c68,69
< void calculateBirthRate()
< {
< birthrate = (double)numberOfBirths/totalCityPopulation;
< }
---
> void calculateBirthRate(PopInfo);
> void calculateDeathRate(PopInfo);
73,76d70
< void calculateDeathRate()
< {
< deathrate = (double)numberOfDeaths / totalCityPopulation;
< }
117,118d110
< newCity.calculateBirthRate();
< newCity.calculateDeathRate();
129a122,125
> void PopInfo::calculateBirthRate(PopInfo newCity)
> {
> double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
> }
130a127,130
> void PopInfo::calculateDeathRate(PopInfo newCity)
> {
> double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
> }

double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
Here you are driving two new variable names birthrate and death rate. You're not writing the values two the class data members. Writing the type before the names overwrites it. To change, simply remove it.
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;

Related

FOR LOOP fails to iterate through the object vector where purchase transactions are stored

I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}

How to allow user input in objects and classes?

Consider the following code:
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber1, int quantity1, double cost1)
{
setItemNumber(itemNumber1);
setQuantity(quantity1);
setCost(cost1);
}
void setItemNumber(int itemNumber2)
{
itemNumber=itemNumber2;
}
bool setQuantity(int quantity2)
{
bool userTrue = true;
bool userFalse = false;
if (quantity2 < 0)
{
quantity = 0;
return userFalse;
}
else
{
quantity= quantity2;
return userTrue;
}
}
bool setCost(double cost2)
{
bool userTrue = true;
bool userFalse = false;
if (cost2 < 0.0)
{
cost = 0.0;
return userFalse;
}
else
{
cost= cost2;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
int total;
total = (quantity * cost);
return total;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
inventory secondObject(itemNumberInput1,quantityInput1,costInput1); // not sure if thats correct
cout << secondObject.setItemNumber(); // not working
cout << secondObject.setQuantity(); // not working
cout << secondObject.setCost(); // not working
return 0;
}
The code above is supposed to take three user inputs, and send them to the classes, and the classes will do their job.
I'm currently stuck at the end where its giving me an error.
In the second object where the values are asked from the user, it should send these values to the classes.
Instead, I'm getting the error.
How can I resolve this problem?
Here is the fixed code:-
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber, int quantity, double cost)
{
this->itemNumber = itemNumber;
this->quantity = quantity;
this->cost = cost;
}
void setItemNumber(int itemNumber)
{
this->itemNumber=itemNumber;
}
bool setQuantity(int quantity)
{
bool userTrue = true;
bool userFalse = false;
if (quantity < 0)
{
this->quantity = 0;
return userFalse;
}
else
{
this->quantity= quantity;
return userTrue;
}
}
bool setCost(double cost)
{
bool userTrue = true;
bool userFalse = false;
if (cost < 0.0)
{
this->cost = 0.0;
return userFalse;
}
else
{
this->cost= cost;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
return quantity * cost;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
// The below line is correct
// inventory secondObject(itemNumberInput1,quantityInput1,costInput1);
//Alternatively
inventory secondObject;
secondObject.setItemNumber(itemNumberInput1);
secondObject.setQuantity(quantityInput1);
secondObject.setCost(costInput1);
delete pointerA; // delete dynamically allocated memory to avoid memory leak
delete pointerB;
return 0;
}
Well you've constructed 'secondObject' object using the 3-arg constructor, using the user-entered values as parameters. Therefore, the member variables of this object are being set via the constructor and using the 'set' methods aren't really necessary. In your case, the set methods would be useful if you wanted to change the values later on. For example, lets pretend the user enters 10, 10, and 2.5 for the values. You're then using the constructor to construct the object with those values. The only difference is you're placing those values into variables first. But it works the same way. If you wanted to change the value of quantity later on, you could do secondObject.setQuantity(2); And the quantity for that object is now set to 2. The reason why your calls to .set aren't working is because you need to pass in parameters to these methods i.e. the value you want to set it to.
In regard to the destructor method being printed, objects are destroyed when they go out of scope so that the memory is released. Normally, nothing would happen in terms of output- the object would just go out of scope and the compiler would free up the memory and go about its' business. However, you've coded a custom destructor that prints out 'The Object is being destroyed', which it is at the end of the main. It's likely your constructor is working fine, I'm just not sure what you expect to be happening. I'd also suggest you read up on memory leaks in C++, especially in regard to the 'new' keyword.

C++ - <error reading characters of string> and "Access violation writing location 0x86A1ECD8"

I'm trying to make a department store program for my school project.
I created a class array for the products to include their names, prices, stock, and number of purchased items to begin with.
But for some reason I get an error as a popup
"Exception thrown at 0x68665139 (vcruntime140d.dll) in Test project.exe:
0xC0000005: Access violation writing location 0x86A1ECD8."
Also, I get an error called error reading characters of string after execution.
Here's my code:
#include<iostream>
#include<string>
using namespace std;
class product {
private:
int stock; //items in stock
int add_stock; //added stock
int purchased; //purchased items(reduces stock)
string name; //name of item
float price; //price of item
public:
//fuctions to input all private variables
void setstock(int x) {
stock = x;
}
void setaddstock(int x) {
add_stock = x;
}
void setpurchased(int x) {
purchased = x;
}
void setname(string x) {
name = x;
}
void setprice(float x) {
price = x;
}
//functions to output all private variables
int getstock() {
return stock;
}
int getaddstock() {
return add_stock;
}
int getpurchased() {
return purchased;
}
string getname() {
return name;
}
float getprice() {
return price;
}
//function that restocks the items
void restock() {
stock += purchased;
}
//function that deducts purchased items from stock
void destock() {
if (stock >= purchased) {
stock -= purchased;
}
else { //in case the purchase demand exceeds items in stock
cout << "\nSorry we only have " << stock << "amount of left\n";
}
}
};
int main() {
int purchased;
product stuff[10]; //class array
int choice, total_qty = 0; //choice-> to choose between products,
total_qty-> total number of products purchased
char yesno; //to choose if user wants to buy anything
else (for do loop)
float total_price = 0; //total amount of money to be paid
// declaring product name and price
stuff[1].setname ("Coconut biscuits");
stuff[1].setprice (12.0);
stuff[2].setname ("Wai Wai noodles"); stuff[2].setprice (20.0);
stuff[3].setname ("Cadbury Dairy Milk"); stuff[3].setprice (45.5);
stuff[4].setname ("Lays"); stuff[4].setprice (50.0);
stuff[5].setname ("Rara Noodles"); stuff[5].setprice (18.5);
stuff[6].setname ("Khajurko Puff"); stuff[6].setprice (50.0);
stuff[7].setname ( "Nanglo Doughnut"); stuff[7].setprice (15.0);
stuff[8].setname ( "Nanglo whole-wheat bread"); stuff[8].setprice (65.0);
stuff[9].setname ("Dabur Real fruit juice"); stuff[9].setprice (30.0);
stuff[10].setname ("Coca-Cola"); stuff[10].setprice (35.5);
// declairing the number of items in stock and setting purchased = 0 for easy calculation
for (int i = 1; i <= 10; i++) {
stuff[i].setstock (100);
stuff[i].setpurchased (0);
}
// displays the menu, make purchase, repeat
cout << "What would you like to buy?\n\n\n";
do {
for (int i = 1; i <= 10; i++) {
cout << i << ". " << stuff[i].getname() << "\n\n"; //displays menu in format: 1. Biscuit
}
cout << "Enter your choice: ";
cin >> choice;
cout << "\n\nHow many of it would you like to buy?";
cin >> purchased;
stuff[choice].setpurchased(purchased);
stuff[choice].destock(); //function for destocking
cout << "\n\nWould you like to buy other items?";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y');
cout << "\n\n\n"; //line spacing, nothing cool here
//this for loop calculates total quantity and price as well as displays the receipt
for (int i = 1; i <= 10; i++) {
total_qty += stuff[i].getpurchased(); //total quantity
total_price += stuff[i].getpurchased() * stuff[i].getprice(); //total price
//only displays if stuff is purchased
if (stuff[i].getpurchased() > 0) {
//format: 1. Biscuit 4 10 40
cout << i << " " << stuff[i].getname() << " " << stuff[i].getpurchased() << " " << stuff[i].getprice() << " " << stuff[i].getpurchased()*stuff[i].getprice() << "\n";
}
}
// displays total price and quantity
cout << "\ntotal quantity: " << total_qty;
cout << "\ntotal price: " << total_price;
return 0;
}
for (int i = 1; i <= 10; i++)
should be
for (int i = 0; i < 10; i++)
You are exceeding your array of products.

Unresolved external symbol "struct MonthlyBudget_cdecl actual(void)"

I can't seem to find the problem in my code whether it be to me being sick or blind I'm unsure of. The error I get is:
unresolved external symbol"struct MonthlyBudget_cdecl actual(void)" (?actual##YA?AUMonthlyBudget##XZ) referenced in function_main.
Any help would be appreciated.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
struct MonthlyBudget {
double housing;
double utilities;
double householdExpenses;
double transportation;
double food;
double medical;
double insurance;
double entertainment;
double clothing;
double misc;
MonthlyBudget(double housingCost, double utilitiesCost, double householdExpensesCost, double transportationCost, double foodCost,
double medicalCost, double insuranceCost, double entertainmentCost, double clothingCost, double miscCost) {
housing = housingCost;
utilities = utilitiesCost;
householdExpenses = householdExpensesCost;
transportation = transportationCost;
food = foodCost;
medical = medicalCost;
insurance = insuranceCost;
entertainment = entertainmentCost;
clothing = clothingCost;
misc = miscCost;
}
MonthlyBudget() {
housing = 0;
utilities = 0;
householdExpenses = 0;
transportation = 0;
food = 0;
medical = 0;
insurance = 0;
entertainment = 0;
clothing = 0;
misc = 0;
}
void setHousing(double housingCost) {
housing = housingCost;
}
double getHousing() {
return housing;
}
void setUtilities(double utilitiesCost) {
utilities = utilitiesCost;
}
double getUtilities() {
return utilities;
}
void setHouseholdExpenses(double householdEXCost) {
householdExpenses = householdEXCost;
}
double getHouseholdExpenses() {
return householdExpenses;
}
void setTransportation(double transportationCost) {
transportation = transportationCost;
}
double getTransportation() {
return transportation;
}
void setFood(double foodCost) {
food = foodCost;
}
double getFood() {
return food;
}
void setMedical(double medicalCost) {
medical = medicalCost;
}
double getMedical() {
return medical;
}
void setInsurance(double insuranceCost) {
insurance = insuranceCost;
}
double getInsurance() {
return insurance;
}
void setEntertainment(double entertainmentCost) {
entertainment = entertainmentCost;
}
double getEntertainment() {
return entertainment;
}
void setClothing(double clothingCost) {
clothing = clothingCost;
}
double getClothing() {
return clothing;
}
void setMisc(double miscCost) {
misc = miscCost;
}
double getMisc() {
return misc;
}
};
int main() {
MonthlyBudget budget(500, 150, 65, 50, 250, 30, 100, 150, 75, 50);
MonthlyBudget actual();
double housing, utilities, householdExpenses, transportation, food, medical, insurance, entertainment, clothing, misc;
cout << "How much did you spend on housing?" << endl;
do {
cin >> housing;
actual().setHousing(housing);
} while (housing < 0);
cout << "How much did you spend on utilities?" << endl;
do {
cin >> utilities;
actual().setUtilities(utilities);
} while (utilities < 0);
cout << "How much did you spend on household expenses?" << endl;
do {
cin >> householdExpenses;
actual().setHousing(householdExpenses);
} while (householdExpenses < 0);
cout << "How much did you spend on transportation?" << endl;
do {
cin >> transportation;
actual().setTransportation(transportation);
} while (transportation < 0);
cout << "How much did you spend on food?" << endl;
do {
cin >> food;
actual().setFood(food);
} while (food < 0);
cout << "How much did you spend on medical?" << endl;
do {
cin >> medical;
actual().setMedical(medical);
} while (medical < 0);
cout << "How much did you spend on insurance?" << endl;
do {
cin >> insurance;
actual().setInsurance(insurance);
} while (insurance < 0);
cout << "How much did you spend on entertainment?" << endl;
do {
cin >> entertainment;
actual().setEntertainment(entertainment);
} while (entertainment < 0);
cout << "How much did you spend on clothing?" << endl;
do {
cin >> clothing;
actual().setClothing(clothing);
} while (clothing < 0);
cout << "How much did you spend on misc?" << endl;
do {
cin >> misc;
actual().setMisc(misc);
} while (misc < 0);
cout << "Showing projected budget compared to actual:" << endl;
cout << "Housing: " << budget.housing - actual().housing << endl;
cout << "Utilities: " << budget.utilities - actual().utilities << endl;
cout << "Household Expenses: " << budget.householdExpenses - actual().householdExpenses << endl;
cout << "Transportation: " << budget.transportation - actual().transportation << endl;
cout << "Food: " << budget.food - actual().food << endl;
cout << "Medical: " << budget.medical - actual().medical << endl;
cout << "Insurance: " << budget.insurance - actual().insurance << endl;
cout << "Entertainment: " << budget.entertainment - actual().entertainment << endl;
cout << "Clothing: " << budget.clothing - actual().clothing << endl;
cout << "Misc: " << budget.misc - actual().misc << endl;
string input;
cin >> input;
return 0;
}//main()
Again thanks for any help! I know the code is pretty messy and there are better ways to do this, but for the life of me I can't think of anything with my flu right now.
Removed () from actual() and all mentions. Fixed the program.

Need help implementing functions in GroceryItem class

Hello I've ran into some trouble creating a GroceryItem class and using functions to accept and set input from a user.
Currently when I run the dataEntry function, the compiler moves on to the next function before accepting input from the first function.
I've created a test milk object to test my code but It doesn't allow me to enter data before moving to the next input prompt.
Once I can figure out the class functions, I will also create an array of objects and input values for such.
Any advice for how I can go about fixing this class and functions would be greatly appreciated!
#include <iostream>
using namespace std;
class GroceryItem{
private: int stockNumber;
double price = 0.0;
int quantity;
double totalValue;
double setPrice();
int setStockNum();
int setQuantity();
void setTotalValue();
public:
void dataEntry();
void displayValues();
};
int GroceryItem::setStockNum(){
int stock = 0;
cout << "Enter the stock number for the grocery item: ";
do {
cout << "Stock Number(1000-9999): ";
cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));
stockNumber = stock;
return stockNumber;
}
double GroceryItem::setPrice(){
double x = 0.0;
cout << "Enter the price of the item: ";
while (!(x > 0)) {
cout << "Please enter a positive number for price!";
cin >> x;
}
price = x;
return price;
}
int GroceryItem::setQuantity(){
int x = 0;
cout << "Enter the quantity in stock: ";
while (!(x > 0)){
cout << "Please enter a positive number for quantity!";
cin >> x;
}
quantity = x;
return quantity;
}
void GroceryItem::setTotalValue(){
totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
setStockNum();
system("pause");
setPrice();
system("pause");
setQuantity();
system("pause");
setTotalValue();
}
void GroceryItem::displayValues(){
cout << "Stock number: " << stockNumber;
cout << "\nItem price: " << price;
cout << "\nQuantity on hand: " << quantity;
cout << "\nTotal value of item: " << totalValue;
}
int main(){
GroceryItem Milk;
Milk.dataEntry();
Milk.displayValues();
system("pause");
return 0;
}
Dude, pay attention to the condition of the while statement, the line
!(stock >= 1000 || stock <= 9999)
returns true for stock = 0 (always true, in this case), so the program won't enter the loop.
Maybe you meant something like:
!(stock >= 1000 && stock <= 9999)
AND(&&) not OR(||)