This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
So here is my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Point
{
private:
double px;
double py;
public:
void setX(const double x);
void setY(const double y);
double getX() const;
double getY() const;
};
class Rectangle
{
private:
string name;
Point blPoint;
double length, height;
public:
// member functions
void setName(const string & inName);
void setBottomLeft(const double x, const double y);
void setDimensions(const double inLength, const double inHeight);
string getName() const;
Point getBottomLeft() const;
double getLength() const;
double getHeight() const;
double area() const;
double perimeter() const;
Point midPoint() const;
void scaleBy2();
void display() const;
};
// FUNCTION PROTOTYPES GO HERE:
void welcome();
bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list);
void read_coord(const string promptPoint, double & x, double & y);
void read_length(const string promptLength, double & inLength, double & inHeight);
void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list);
int main()
{
// Define your local variables, e.g. a vector of class Rectangle
Rectangle rec;
vector<Rectangle> list;
string prompt1stName = "Enter the name of the first rectangle: ";
string promptName = "Enter the name of the next rectangle: ";
string errorInvalid = "Invalid input. Type 'rec' following by the name or 'stop' if done.";
string errorUsed = "This name is already being used!";
string inName;
string Name;
// Display welcome banner
welcome();
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
// IF user input is not 'stop'
if (inName != "stop")
{
// Extract rectangle name from user input
int a = inName.length() - 4;
Name = inName.substr(4, a);
// Prompt for bottom left point
double x, y;
string promptPoint = "Enter " + Name + "'s bottom left x and y coords: ";
read_coord(promptPoint, x, y);
// Prompt for length and height
double inLength, inHeight;
string promptLength = "Enter " + Name + "'s length and height: ";
read_length(promptLength, inLength, inHeight);
// Add rectangle to the rectangle list
add_rec(Name, x, y, inLength, inHeight, list);
}
/* Prompt user for next rectangle or 'stop' */
// WHILE user input not 'stop'
while (inName != "stop")
{
// Display "Thank you! "
cout << "Thank you! ";
bool read = read_rec(promptName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(promptName, errorInvalid, errorUsed, inName, list);
}
// IF user input is not 'stop'
if (inName != "stop")
{
// Extract rectangle name from user input
int a = inName.length() - 4;
Name = inName.substr(4, a);
// Prompt for bottom left point
double x, y;
string promptPoint = "Enter " + Name + "'s bottom left x and y coords: ";
read_coord(promptPoint, x, y);
// Prompt for length and height
double inLength, inHeight;
string promptLength = "Enter " + Name + "'s length and height: ";
read_length(promptLength, inLength, inHeight);
// Add rectangle to the rectangle list
add_rec(Name, x, y, inLength, inHeight, list);
}
}
// IF the rectangle list is not empty
if (list.size() != 0)
{
// Display all rectangles in the rectangle list
int rec_num = 0;
int i = 1;
while (i< list.size())
{
rec_num++;
i++;
}
cout << "You have " << rec_num+1 << " rectangle(s) in your list: ";
cout << endl;
for (int i = 0; i < list.size(); i++)
{
cout << "Rectangle '" << list[i].getName() << "' : ";
list[i].display();
list[i].scaleBy2();
cout << " After scale by 2: ";
list[i].display();
cout << endl;
}
}
// ELSE
else
{
// Display that no rectangles are in the list
cout << "You have no rectangles in your list." << endl;
}
return 0;
}
// FUNCTION DEFINITIONS GO HERE:
void welcome()
{
cout << "Welcome! Create your own list of rectangles." << endl;
cout << "You will be asked to provide information about each rectangle in your list by name." << endl;
cout << "Type the word 'stop' for the rectangle name when you are done." << endl;
cout << endl;
}
bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list)
{
cout << promptName;
getline(cin, inName);
if (inName == "stop")
{
return(true);
}
else if (inName.substr(0,4) != "rec ")
{
cout << errorInvalid;
return(false);
}
else
{
int j = 0;
for (int i = 0; i < list.size(); i++)
{
if (inName == "rec " + list[i].getName())
{
j = j+1;
}
}
if (j == 0)
{
return(true);
}
if (j != 0)
{
cout << errorUsed;
return(false);
}
}
}
void read_coord(const string promptPoint, double & x, double & y)
{
cout << promptPoint;
cin >> x;
cin >> y;
}
void read_length(const string promptLength, double & inLength, double & inHeight)
{
cout << promptLength;
cin >> inLength;
cin >> inHeight;
cout << endl;
while (inLength <= 0 || inHeight <= 0)
{
cout << "Make length and height positive values. Try again.";
cout << promptLength;
cin >> inLength;
cin >> inHeight;
cout << endl;
}
}
void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list)
{
Rectangle rec;
rec.setName(Name);
rec.setBottomLeft(x, y);
rec.setDimensions(inLength, inHeight);
list.push_back(rec);
}
// CLASS MEMBER FUNCTION DEFINITINOS GO HERE:
void Point::setX(const double x)
{
px = x;
}
void Point::setY(const double y)
{
py = y;
}
double Point::getX() const
{
return (px);
}
double Point::getY() const
{
return (py);
}
void Rectangle::setName(const string & inName)
{
name = inName;
}
void Rectangle::setBottomLeft(const double x, const double y)
{
blPoint.setX(x);
blPoint.setY(y);
}
void Rectangle::setDimensions(const double inLength, const double inHeight)
{
length = inLength;
height = inHeight;
}
string Rectangle::getName() const
{
return (name);
}
Point Rectangle::getBottomLeft() const
{
return (blPoint);
}
double Rectangle::getLength() const
{
return (length);
}
double Rectangle::getHeight() const
{
return (height);
}
double Rectangle::area() const
{
// area = length * height
return(length * height);
}
double Rectangle::perimeter() const
{
// perimeter = 2 * (length + height);
return(2 * (length + height));
}
Point Rectangle::midPoint() const
{
Point midPoint;
double mx = blPoint.getX() + 0.5 * length;
double my = blPoint.getY() + 0.5 * height;
midPoint.setX(mx);
midPoint.setY(my);
return(midPoint);
}
void Rectangle::scaleBy2()
{
double midx = blPoint.getX() + 0.5 * length;
double midy = blPoint.getY() + 0.5 * height;
double newblPx = midx - length;
double newblPy = midy - height;
length = 2*length;
height = 2*height;
blPoint.setX(newblPx);
blPoint.setY(newblPy);
}
void Rectangle::display() const
{
cout << " Location is (" << blPoint.getX() << ", " << blPoint.getY() << "), length is " << length << ", height is " << height << "; Area is " << area() << "; perimeter is " << perimeter() << ", midpoint is located at (" << midPoint().getX() << ", " << midPoint().getY() << ")" << endl;
}
The only problem's I now have with the program is that it always outputs "Invalid input. Type 'rec' following by the name or 'stop' if done.", and i do not know how to change this. And when you put in a duplicate answer as in rec fire and rec fire, it will say that rec fire is already being used and then continue to prompt for that rectangle instead of asking for another name. ANY HELP would be much appreciated!!
This is wrong
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
You have two read variables, the read variable in the while condition is referring to the read variable declared first, the read variable declared second is never used. What you want is this
/* Prompt user for first rectangle or 'stop' */
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
// WHILE user input is invalid
while (read == false)
{
// Display "Try again! "
cout << "Try again! " << endl;
read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
}
Now you have only one read variable. This accounts for the second error you describe I think.
Another way of coding this is like this
for (;;)
{
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list);
if (read)
break;
cout << "Try again! " << endl;
}
In my view this kind of loop is better because it doesn't have the duplicated call to read_rec, so with this style of loop the mistake you made is impossible.
Related
This question already has answers here:
Default constructor error no matching function for call to
(2 answers)
C++ array of a self-defined class, no matching function call
(3 answers)
no matching function to call for "constructor"
(1 answer)
Closed last year.
I'm a beginner in c++. Though the code is still incomplete, I would like to know why I'm not able to create an array to store my objects from the class. I have to store 5 bank accounts in an array and I was trying to do so by soring the objects but it keeps showing error.
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class Bank
{
string depositor;
int accno;
char type;
float balance;
public:
Bank(string depositor, int accno, char type, float balance); //to assign initial values
void deposit(); //to deposit amount
float withdraw(); //to withdraw amount
void show(); //to show name and balance
Bank(string depositor, int accno); //constructor function for name and account no.
Bank(float balance, int accno); //constructor function for balance and account no.
Bank(char type, int accno); //constructor function for type and account no.
Bank(const Bank&); //copy constructor
//getter and setter functions for all data members
void setname(string depositor);
void setacc(int accno);
void settype(char type);
void setbal(float balance);
string getname();
int getacc();
char gettype();
float getbal();
};
Bank::Bank(string depos, int acno, char typ, float bal)
{
depositor=depos;
accno = acno;
type = typ;
balance = bal ? bal : 0;
}
void Bank::deposit()
{
float damt1;
cout << "Enter deposit amount: ";
cin >> damt1;
if (damt1 < 0.0) {
cout << "Can't deposit negative amount." << endl;
damt1 = 0.0;
}
balance += damt1;
}
float Bank::withdraw()
{
int amount;
cout << "Enter withdrawal amount: ";
cin >> amount;
if (amount < 0.0) {
cout << "Negative amount can't be withdrawn" << endl;
amount = 0;
}
if (amount > balance - 1000.0) {
cout << "Not enough balance.";
}
balance -= amount;
return amount;
}
Bank::Bank(string name, int no)
{
depositor = name;
accno = no;
}
Bank::Bank(float bal, int no)
{
balance = bal;
accno = no;
}
Bank::Bank(char ty, int no)
{
type = ty;
accno = no;
}
Bank::Bank(const Bank& p)
{
balance = p.balance;
accno = p.accno;
}
void Bank::setname(string name)
{
depositor = name;
}
void Bank::setacc(int n)
{
accno = n;
}
void Bank::settype(char ty)
{
type = ty;
}
void Bank::setbal(float bal)
{
balance = bal?bal:0;
}
string Bank::getname()
{
return depositor;
}
int Bank::getacc()
{
return accno;
}
char Bank::gettype()
{
return type;
}
float Bank::getbal()
{
return balance;
}
void Bank::show()
{
cout << "Name: " << depositor<<endl;
cout << "Account number: " << accno<<endl;
cout << "Type: " << type<<endl;
cout << "Balance: " << balance<<endl;
}
int main()
{
Bank acct[5];//This is the line with error.I am unable to complete the code bcoz of this
int acno,i;
char ty;
string name;
float bal;
for (i=0;i<5;i++){
cout << "Enter details: \n";
cout << "name: ";
cin >> name;
cout << "\nEnter accno: ";
cin >> acno;
cout << "\nEnter type: ";
cin >> ty;
cout << "\nEnter balance: ";
cin >> bal;
Bank b1(name, acno, ty, bal);
}
return 0;
}
Can someone help me with what corrections I should make?
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);
}
Generally I have a class named "person" and its methods, print: to print the data, and is_better_than to find some max numbers. I cannot understand what is the problem. Any advice?
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class person
{
private:
string name;
double weight;
double height;
public:
person(); //Constructor
bool is_better_than(person best);
void read();
void print();
void operator=(const person& b); //overloading operator
};
person::person()
{
string name = "";
double weight = 0;
double height = 0;
}
void person::print()
{
cout << name << "\nWeight: " << weight << "\nHeight: " << height << "\n";
}
void person::read()
{
cout << "Please enter person's name: ";
getline(cin, this->name);
cout << "Please enter person's weight: ";
cin >> this->weight;
cout << "Please enter person's height: ";
cin >> this->height;
string remainder;
getline(cin, remainder); //clear the buffer
}
bool person::is_better_than(person best)
{
if ((this->weight / pow(this->height,2) >= best.weight / (pow(best.height,2))) || best.weight == 0)
return true;
return false;
}
// iperfortosi telesti =
void person::operator=(const person & b)
{
this->name = b.name;
this->weight = b.weight;
this->height = b.height;
}
int main()
{
person maxBMI;
bool cont = true;
while (cont)
{
person newperson;
newperson.read();
if (newperson.is_better_than(maxBMI))
maxBMI = newperson;
cout << "More data? (y/n) ";
string answer;
getline(cin, answer);
if (answer != "y")
cont = false;
}
cout << "The person with maximum BMI (body mass index) is ";
maxBMI.print();
return 0;
}
Output:
Please enter person's name: Name
Please enter person's weight: 123
Please enter person's height: 123
More data? (y/n) n
The person with maximum BMI (body mass index) is
Weight: 1.7881e-307
Height: 2.0746e-317
Your default constructor does not work because it assigns to local variables and not to class variables. It should look like this:
person::person()
{
name = "";
weight = 0;
height = 0;
}
or better:
person::person() : name(""), weight(0.0), height(0.0) {}
With your default constructor, the class attributes remain uninitialized and the assumption that best.weightis initially zero, does not work.
Okay so i created program that simulates a landscaping company and so we have to calculate the cost of Sod and fence. So when i enter in both the length and width they out put huge decimals for example
Parkton Landscaping
Enter Length: 10
Enter width: 12
Lanscaping Costs
Sod = 6871947680.00
Fence = 19327352760.00
Press any key to continue . . .
Sod is suppose to = 56.40
and Fence is suppose to = 990.00
please help here is my code and both files
#include <iostream>
#include <iomanip>
using namespace std;
#include "c:\Users\barta\OneDrive\Documents\Visual Studio 2015\Projects\Project 6\Project 6\Geometry.h"
#include "Pricing.h"
int main()
{
int length, width;
Pricing landscape;
Geometry geo;
const double Fenceprice = 22.50;
const double Sodprice = .47;
cout << "\t Parkton Landscaping " << endl;
cout << "Enter Length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
//Pricing(length, width);
//geo.getLength();
//geo.getWidth();
std::cout << std::fixed << std::setprecision(2);
landscape.displayOutput();
cout << "Sod = " << landscape.getsodCost(length) << endl;
cout << "Fence = " << landscape.getFenceCost(Fenceprice) << endl;
system("pause");
return 0;
}
here is the header file:
#pragma once
class Geometry
{//an object is how you access the class
public:// where the public function definitions are created
Geometry();// Default Constructor
Geometry(int, int);
Geometry(int);
void setLength(int); //assigns length
void setWidth(int); //assigns width
void setSide(int); //assigns side
//Constructor function that recieves the values for the rectangle
//Constructor function that recieves values for the cube
int getLength(),
getWidth(),
getSide(),
getArea(),
getPerimeter(),
getSurfaceArea();
private: //where the private members are created
int length,
width,
side;
void checkNum(int); //function that checks to see if the number is less than 0
};
Geometry::Geometry()
{
length = length;
width = width;
side = 0;
}
Geometry:: Geometry(int length, int width) /*function recieves 2 intergers and calls checkNum to validate if */
{
setLength(length);
setWidth(width);
checkNum(length);
checkNum(width);
}
Geometry:: Geometry(int sides)
{
checkNum(sides);
setSide(sides);
}
int Geometry::getLength()
{
return length;
}
int Geometry::getWidth()
{
return width;
}
int Geometry::getSide()
{
return side;
}
int Geometry::getArea()
{
return length * width;
}
int Geometry::getPerimeter()
{
return 2 * (length + width);
}
int Geometry::getSurfaceArea()
{
return 6 * (side * side);
}
void Geometry::setLength(int len)
{
length = len;
checkNum(len);
}
void Geometry::setWidth(int widths)
{
width = widths;
checkNum(widths);
}
void Geometry::setSide(int s)
{
side = s;
checkNum(s);
}
void Geometry::checkNum(int num) //function checks to see if the number is less than zero
{
if (num <= 0)
{
cout << "!!!!!!!!WARNING!!!!!! this isnt a number" << " program will now exit......" << endl;
system("pause");
exit(1);
}
}
Header file #2
#include "Geometry.h"
class Pricing : Geometry
{
public:
Pricing();
Pricing(int length, int width);
double getsodCost(double);
double getFenceCost(double);
void displayOutput();
private:
};
Pricing::Pricing(int length, int width) :Geometry(length, width)
{
}
Pricing::Pricing()
{
}
double Pricing::getsodCost(double price)
{
getArea();
return getArea()*price;
}
double Pricing::getFenceCost(double price)
{
getPerimeter();
return getPerimeter()*price;
}
void Pricing::displayOutput()
{
cout << "\n\n";
cout << "\t Lanscaping Costs " << endl;
}
Because you never initialize the objects with valid values, meaning Geometry::width and Geogrpapy::length are uninitialized and have indeterminate values. Using them uninitialized leads to undefined behavior.
One of my last assignments in C++ course is to write this program:
Reads a name for rectangle and just accepts names like "rec" name. for
example "rec john" "rec sally" ...
Then asks from bottom left point x
and y, as well as height and length. Then displays some info including
BL point, area, perimeter,...
Here is the code I wrote. I was working on it for a long time so now I really cannot see what is wrong with it. So please help.
My code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Point
{
private:
double px;
double py;
public:
void setX(const double x);
void setY(const double y);
double getX() const;
double getY() const;
};
class Rectangle
{
private:
string name;
Point blPoint;
double length, height;
public:
void setName(const string & inName);
void setBottomLeft(const double x, const double y);
void setDimensions(const double inLength, const double inHeight);
string getName() const;
Point getBottomLeft() const;
double getLength() const;
double getHeight() const;
double area() const;
double perimeter() const;
Point midPoint() const;
void scaleBy2();
void display() const;
};
void welcome();
bool read_rect (const string promptName, const string errInvalidName, const string errUsedName, string & inName, vector<Rectangle> & list);
void readXYcoord (const string promptPointxy, double & xcord, double & ycord);
void readLH (const string promptLH, double & inLength, double & inHeight);
void addRect (const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list);
void dis_rec(vector<Rectangle> & list);
int main()
{
Rectangle rec;
vector<Rectangle>list;
string prompt1stName = "Enter the name of the first rectangle: ";
string promptName = "Enter the name of the next rectangle: ";
string errInvalidName = "Invalid input. Type 'rec' following by the name or 'stop' if done.";
string errUsedName = "This name is already being used!";
string inName;
string Name;
double x,y,length,height;
welcome ();
bool read = read_rect (prompt1stName, errInvalidName, errUsedName, inName, list);
while (read == false)
{
cout << "Try again! ";
read = read_rect (prompt1stName, errInvalidName, errUsedName, inName, list);
}
if (inName != "stop")
{
int a = inName.length() - 4;
Name = inName.substr(4,a);
double x, y;
string promptPointxy = "Enter " + Name + "'s bottom left x and y coords: ";
readXYcoord (promptPointxy, x, y);
double length, height;
string promptLH= "Enter " + Name + "'s length and height: ";
readLH (promptLH, length, height);
addRect(Name, x, y, length, height, list);
}
while (inName !="stop")
{
cout << "Thank you! ";
bool read = read_rect(promptName, errInvalidName, errUsedName, inName, list);
while (read == false)
{
cout << "Try again! " <<endl;
read = read_rect(promptName, errInvalidName, errUsedName, inName, list);
}
if (inName != "stop")
{
int a = inName.length() - 4;
Name = inName.substr(4, a);
double x, y;
string promptPoint = "Enter " + Name + "'s bottom left x and y coords: ";
readXYcoord(promptPoint, x, y);
double inLength, inHeight;
string promptLength = "Enter " + Name + "'s length and height: ";
readLH(promptLength, inLength, inHeight);
addRect(Name, x, y, inLength, inHeight, list);
}
}
if (list.size() != 0)
{
dis_rec(list);
}
else
{
cout << "You have no rectangles in your list." << endl;
}
return 0;
}
void welcome()
{
cout << "Welcome! Create your own list of rectangles." << endl;
cout << "You will be asked to provide information about each rectangle in your list by name." << endl;
cout << "Type the word 'stop' for the rectangle name when you are done." << endl;
cout << endl;
}
bool read_rect (const string promptName, const string errInvalidName, const string errUsedName, string & inName, vector<Rectangle> & list)
{
cout << promptName;
getline(cin, inName);
if (inName == "stop")
{
return (true);
}
else if (inName.substr(0,4) != "rec ")
{
cout<< errInvalidName <<endl;
return (false);
}
else
{
int j = 0;
for (int i = 0; i < list.size(); i++)
{
if (inName == "rec " + list[i].getName())
{
j = j+1;
}
}
if (j == 0)
{
return(true);
}
if (j != 0)
{
cout << errUsedName;
return(false);
}
}
}
void readXYcoord (const string promptPointxy, double & xcord, double & ycord)
{
cout << promptPointxy;
cin >> xcord;
cin >> ycord;
}
void readLH (const string promptLH, double & inLength, double & inHeight)
{
cout<< promptLH;
cin >> inLength;
cin >> inHeight;
cout << endl;
while (inLength <= 0 || inHeight <= 0)
{
cout << "Make length and height positive values. Try again.";
cout << promptLH;
cin >> inLength;
cin >> inHeight;
cout << endl;
}
}
void addRect (const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list)
{
Rectangle rec;
rec.setName(Name);
rec.setBottomLeft(x, y);
rec.setDimensions(inLength, inHeight);
list.push_back(rec);
}
void dis_rec(vector<Rectangle> & list)
{
cout<<"You have "<<list.size()<<" rectangle(s) in your list: "<<endl;
for(int i=0; i<list.size(); i++)
{
cout<<"Rectangle '"<<list[i].getName()<<"': ";
list[i].display();
cout<<"After scale by 2:";
list[i].scaleBy2();
list[i].display();
}
}
void Point::setX(const double x)
{
px = x;
}
void Point::setY(const double y)
{
py = y;
}
double Point::getX() const
{
return (px);
}
double Point::getY() const
{
return (py);
}
void Rectangle::setName(const string & inName)
{
name = inName;
}
void Rectangle::setBottomLeft(const double x, const double y)
{
blPoint.setX(x);
blPoint.setY(y);
}
void Rectangle::setDimensions(const double inLength, const double inHeight)
{
length = inLength;
height = inHeight;
}
string Rectangle::getName() const
{
return (name);
}
Point Rectangle::getBottomLeft() const
{
return (blPoint);
}
double Rectangle::getLength() const
{
return (length);
}
double Rectangle::getHeight() const
{
return (height);
}
double Rectangle::area() const
{
return(length*height);
}
double Rectangle::perimeter() const
{
return ( (height*2)+(length*2));
}
Point Rectangle::midPoint() const
{
Point midPoint;
double mpx = blPoint.getX() + 0.5 * length;
double mpy = blPoint.getY() + 0.5 * height;
midPoint.setX(mpx);
midPoint.setY(mpy);
return(midPoint);
}
void Rectangle::scaleBy2()
{
double mx = blPoint.getX() + 0.5 * length;
double my = blPoint.getY() + 0.5 * height;
double newmdx = mx - length;
double newmdy = my - height;
length= 2* length;
height = 2* height;
blPoint.setX(newmdx);
blPoint.setY(newmdy);
}
void Rectangle::display() const
{
cout << " Location is (" << blPoint.getX() << ", " << blPoint.getY() << "), length is " << length << ", height is " << height << "; Area is " << area() << "; perimeter is " << perimeter() << ", midpoint is located at (" << midPoint().getX() << ", " << midPoint().getY() << ")" << endl;
}
here is the corrects output for correct input:
Welcome! Create your own list of rectangles.
You will be asked to provide information about each rectangle in your list by name.
Type the word 'stop' for the rectangle name when you are done.
Enter the name of the first rectangle: rec john
Enter john's bottom left x and y coords: 2
3
Enter john's length and height: 4
5
Thank you! Enter the name of the next rectangle: stop
You have 1 rectangle(s) in your list:
Rectangle 'john': Location is (2, 3), length is 4, height is 5; Area is 20, perimeter is 18, midpoint is located at (4, 5.5)
After scale by 2: Location is (0, 0.5), length is 8, height is 10; Area is 80, perimeter is 36, midpoint is located at (4, 5.5)
and here is my program's response:
Welcome! Create your own list of rectangles.
You will be asked to provide information about each rectangle in your list by na
me.
Type the word 'stop' for the rectangle name when you are done.
Enter the name of the first rectangle: rec john
Enter john's bottom left x and y coords: 2
3
Enter john's length and height: 4
5
Thank you! Enter the name of the next rectangle: Invalid input. Type 'rec' follo
wing by the name or 'stop' if done.
Try again!
Enter the name of the next rectangle: stop
You have 1 rectangle(s) in your list:
Rectangle 'john': Location is (2, 3), length is 4, height is 5; Area is 20; per
imeter is 18, midpoint is located at (4, 5.5)
After scale by 2: Location is (0, 0.5), length is 8, height is 10; Area is 80; p
erimeter is 36, midpoint is located at (4, 5.5)
As you can see, the only problem with this program is it displays the errInvalidName before asking for the next rectangle's name and info. what is wrong?
Your problem lies in combining cin >> with getline. Those two things aren't quite compatible, since they use a different mechanism to get the input. To fix the problem, after every cin >> in your program, you should also add cin.ignore().
The difference between those two methods is, that the overloaded operator >> gets the content before the newline character, and leaves the newline char in the buffer. When you use getline after doing >>, you extract the empty line. The empty line isn't "stop", and doesn't begin with "rec", so your program prompts an error.