loops in headers or main file - c++

So I put a while loop in my header file and I wanted to connect it to my main.cpp but then my main.cpp is not playing it unless it is stated like in my header file. So I'm wondering if a while loop in the header even necessary? The assignment is to create a program that calculates the user's salary given her sales.
This is my header file:
class Salary
{
public:
Salary(){};
Salary(double employeeSales, double employeeSalary)
:sales{employeeSales},salary(employeeSalary)
{
while(employeeSales != -1)
{
salary = 200 + (.09 * sales);
}
}
void setSales(double employeeSales)
{
sales = employeeSales;
}
void setSalary(double employeeSalary)
{
salary = employeeSalary;
}
double getSales() const{return sales;}
double getSalary() const{return salary;}
private:
double sales;
double salary;
};
this is my main.cpp
#include <iostream>
#include <iomanip>
#include "Salary.h"
using namespace std;
int main()
{
Salary mySalary;
double employeeSales;
double employeeSalary;
cout << fixed << setprecision(2);
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
mySalary.setSales(employeeSales);
while(true)
{
employeeSalary = 200 + (.09 * employeeSales);
mySalary.setSalary(employeeSalary);
cout << "Salary is: $" << mySalary.getSalary();
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
mySalary.setSales(employeeSales);
}
}
However the while loop in main won't work unless i put while(employeeSales != -1)

Rather than have your constructor handle garbage data (-1 as the argument), just create an if statement in the while-loop in main that breaks if the user entered -1.
while(true)
{
employeeSalary = 200 + (.09 * employeeSales);
mySalary.setSalary(employeeSalary);
cout << "Salary is: $" << mySalary.getSalary();
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
if( employeeSales == -1)
{
cout << "Stopping program!" << endl;
break; // exits the while loop
}
mySalary.setSales(employeeSales);
}
Doing this allows for a while-loop in your Salary constructor to be unnecessary, and should hopefully solve your issue.

Related

Calculations wont display in output

I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}

Exception catch string is not allowing equation to process correctly

I have created an solution that compiles correctly, but when I enter in the required input it provides only a value of '0' which is not correct. It started when I amended the code to have exception handling but for some reason now, the code no longer processes. The first three input values can be anything and it will still output '0' when run. Thoughts?
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
private:
double loan, interest;
int years;
public:
MortgageCalc() = default;
void setLoan(double l) { loan = l; } //mutator
void setIntrest(double i) { interest = i; } //mutator
void setYears(short y) { years = y; } //mutator
double getMonthlyDue(double term) { return ((loan * ((interest / 100) / 12) * term) / (term - 1)); } //constructor to run math calculation on montly loan amou
double getTotalDue(double term) { return (getMonthlyDue(term) * (years * 12)); } //constructor to compute total amount with interest
double getTotalInt(double term) { return (getTotalDue(term) - loan); }
};
int main()
{
MortgageCalc mort1;
int choice = 0;
int years = 0;
double term(0), loan(0), interest(0);
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
// cout << "Loan amount cannot be negative. Enter the amount: ";
mort1.setLoan(loan);
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest; {
if (interest <= 0) { //example if you put 0 or negative # an exception will throw
throw std::invalid_argument("received negative value"); //example #2 of negative throw exception
}
}
// cout << "Interest rate cannot be negative. Enter the amount: ";
mort1.setIntrest(interest);
cout << "Enter the length of the loan in years: "; //establishes term of payments
while (!(cin >> years) || years < 0)
cout << "Remainder of loan period cannot be negative. Enter the amount: ";
mort1.setYears(years);
term = pow((1 + ((interest / 100) / 12)), (12 * years)); //simple interest calculation with power calc to establish whole number translation
while (choice != 3) //loop for menu options and clean function exit
{
cout << endl;
cout << "Program to Calculate Mortgage Payments" << endl <<
"1. Monthly Payment" << endl <<
"2. Total Payment" << endl <<
"3. Exit" << endl << endl <<
"Enter an option above: ";
cin >> choice;
if (choice == 1)
cout << "Monthly payment due is " << mort1.getMonthlyDue(term) << "." << endl;
else if (choice == 2)
cout << "Total amount for entire loan payments plus interest is $" << mort1.getTotalDue(term) << "." << endl <<
"Total Interest Paid for this loan amount $" << mort1.getTotalInt(term) << "." << endl;
}
return 0;
}
Your problem is that when you do
mort1.setLoan(loan);
loan will always be 0 unless cin >> loan; throws an std::sting. When you use
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
You have your conversion code from a string into the double1 in the catch statement. You will only ever enter that statement if cin >> loan; throws a std::string which I do not believe will ever happen. Since you never actually update the value of loan in main it stays at the 0 you initialized it with.
You should only be doing error handling in the catch block. The code to convert the string to a double should be handled outside the catch block. I think you need to revisit how exceptions work and you should also look into how scopes can hide names from the outer scope.
1 This is also not going to work since you are hiding the double loan from main with the string loan declared inside the sub scope. You need to use different names for the variables in the sub scope.

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(||)

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

Trying to call functions from class

I am trying to execute the code inside of a .h File by creating an object.. What am I doing wrong?
//TicketFineCalculator.h
#include <iostream>
using namespace std;
class TicketFineCalculator
{
public:
int getFine() {
int procFee, zone, speedLimit, actualSpeed, totalFine;
int anotherRun = 1;
while (anotherRun == 1){
cout << "\n-------------------------------";
cout << "\nSpeeding Ticket Fine Calculator";
cout << "\n-------------------------------";
cout << "\nEnter processing fee, in dollars:";
cin >> procFee;
cout << "\nSpeeding Ticket #1";
cout << "\nEnter the type of speeding offense (1 for regular, 2 for work zone, 3 for residential district):";
cin >> zone;
cout << "\nEnter the speed limit, in miles per hour:";
cin >> speedLimit;
cout << "\nEnter the vehicle's speed, in miles per hour:";
cin >> actualSpeed;
cout << "\nThe total fine is:" << totalFine;
cout << "\nEnter 1 to enter process another speeding ticket or 0 to quit:";
cin >> anotherRun;
} // terminates while loop
return totalFine;
}
// Calculate the total fine given the road zone, speed limit, and the vehicle's actual speed.
// Return the fine as an integer.
};
//Project1.cpp
#include <iostream>
#include "TicketFineCalculator.h"
int totalFine;
TicketFineCalculator::getFine(totalFine);
int main(){
cout << totalFine;
return 0;
} //terminates main
If you want to call the getFine() method within TicketFineCalculator, you must declare the method static as in:
class TicketFineCalculator
{
public:
static getFine()
{
}
};
or you must create an instance of TicketFineCalculator and call the method using that instance.