this is my first time posting here, so be a little gentle ok? Also, I am taking my first programming class, and though I understand everything we are doing in class, a lot of the stuff I read on here is over my head. If you could please try to keep your answers as basic as possible I would appreciate it.
With that said, I am doing C++ programming, using code blocks on a mac.
This is the error I am getting from code blocks
Undefined symbols for architecture x86_64:
"totalBill(double, char, double&, double&, double&, double&)", referenced from:
_main in Watkins-wk6-prog1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Process terminated with status 1 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
I will also post the code so you can take a look and see if that sheds any light.
#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;
//Global Constants
double const COM_PRICE = 22.91;
double const MID_PRICE = 25.76;
double const FULL_PRICE = 28.87;
double const SUV_PRICE = 98.88;
int const COM_MILES = 20;
int const MID_MILES = 25;
int const FULL_MILES = 30;
string const SUV_MILES = "Unlimited";
double const COM_OVER_MILES = 0.05;
double const MID_OVER_MILES = 0.07;
double const FULL_OVER_MILES = 0.09;
string const SUV_OVER_MILES = "N/A";
int const WEEK = 7;
double const WEEK_RATE = 6.5;
double const TAX = .115;
string const PROMPT1 = "Enter the number of days for the rental";
string const PROMPT2 = "Enter the number of miles driven";
string const PROMPT3 = "Enter the type of car to be rented (C,M,F,S)";
// function prototypes
char carSize(string prompt);
double inputs (string prompt);
double ChargeForCar(char carType, int numDays);
double carPrice (char carType);
double ChargeforMiles(double miles, char carType);
void totalBill(double miles, char carType, double& taxTotal, double& mileCharge, double&
grandTotal, double& carCharge);
string carSize (char carType);
void billOutput(string carTypeName, int numDays, double miles, double carCharge, double
milageCharge, double taxTotal, double grandTotal);
int main()
{
int numDays; // number of days of rental
int weeks ; // number of weeks in rental period
int extraDays; // number of extra days if car rented for more than a week
double mileCharge = 0;
double carCharge = 0;
double taxTotal = 0;
double grandTotal = 0;
char carType;
double miles;
string carTypeName;
cout << "Program to calculate the charge for a rental car." << endl << endl;
carType = carSize(PROMPT3); // calls function to get the type of car from
// the user
numDays = static_cast<int> (inputs(PROMPT1)); // calls function to get number of days in
//the rental period
miles = inputs(PROMPT2); // calls function to get number of mile driven
// during rental period
// calls function to calculate the total rental car bill
totalBill(miles, carType, taxTotal, grandTotal, mileCharge, carCharge);
carTypeName = carSize(carType); // calls function to save car size as string
//calls function to output the bill componenets
billOutput(carTypeName, numDays, miles, carCharge, mileCharge, taxTotal, grandTotal);
return 0;
}
char carSize(string prompt) // function to present car choices and read in user input
{
char carType;
bool valid = false;
cout << "Type of Car" << setw(16) << "Price per day" << setw(15);
cout << "Included Milage" << setw(24) << "Extra charge per mile" << endl;
cout << setw(66) << setfill ('-') << "-" << endl;
cout << setfill(' ') << "C - Compact size" << setw(8) << COM_PRICE;
cout << setw(5) << COM_MILES << setw(5) << COM_OVER_MILES << endl;
cout << "M - Mid-Size" << setw(8) << MID_PRICE;
cout << setw(5) << MID_MILES << setw(5) << MID_OVER_MILES << endl;
cout << "F - Full size" << setw(8) << FULL_PRICE << setw(5) ;
cout << FULL_MILES << setw(5) << FULL_OVER_MILES << endl;
cout << " S - SUV" << setw(8) << SUV_PRICE << setw(5) ;
cout << SUV_MILES << setw(5) << SUV_OVER_MILES << endl;
do
{
cout << prompt ;
cin >> carType;
carType = toupper(carType);
switch(carType)
{
case 'C':
case 'F':
case 'M':
case 'S':
valid = true;
break;
default:
cout << "Invalid entry. Please enter a letter from the list";
break;
}
}
while (valid == false);
return carType;
}
double inputs(string prompt) // general function to read a prompt and output user input
{
double input;
do
{
cout << prompt;
cin >> input;
if (input <= 0)
{
cout << "Invalid input." << endl;
cout << "Please enter a positive, nonzero interger." << endl;
}
}
while (input <= 0);
return input;
}
double ChargeForCar(char carType, int numDays) // function to calculate the charge for the
//rental period
{
double carCharge;
int weeks;
int extraDays;
double carRate;
carRate = carPrice(carType);
if (numDays >= WEEK)
{
weeks = numDays / WEEK;
extraDays = numDays % WEEK;
carCharge = (weeks * WEEK_RATE * carRate) + (extraDays * carRate);
}
else
{
carCharge = carRate * numDays;
}
return carCharge;
}
double carPrice (char carType) // function to determine which price to use for rental car
{
double carRate;
switch (carType)
{
case 'C':
carRate = COM_PRICE;
break;
case 'F':
carRate = FULL_PRICE;
break;
case 'M':
carRate = MID_PRICE;
break;
case 'S':
carRate = SUV_PRICE;
break;
default:
cout << "Unknown car type" << endl;
break;
}
return carRate;
}
double ChargeForMiles(double miles, char carType) // function to calculate the extra milage
//cost
{
double milesCost;
double extraMiles;
switch(carType)
{
case 'C':
if (miles > COM_MILES)
{
extraMiles = miles - COM_MILES;
milesCost = extraMiles * COM_OVER_MILES;
}
else
{
milesCost = 0;
}
break;
case 'F':
if (miles > FULL_MILES)
{
extraMiles = miles - FULL_MILES;
milesCost = extraMiles * FULL_OVER_MILES;
}
else
{
milesCost = 0;
}
break;
case 'M':
if (miles > MID_MILES)
{
extraMiles = miles - MID_MILES;
milesCost = extraMiles * MID_OVER_MILES;
}
else
{
milesCost = 0;
}
break;
}
return milesCost;
}
void totalBill(double miles, double numDays, char carType, double& taxTotal, double& mileCharge,
double& grandTotal, double& carCharge)
// function to calculate the program totals
{
switch(carType)
{
case 'C':
case 'M':
case 'F':
mileCharge = ChargeForMiles(miles, carType);
break;
default:
mileCharge = 0;
break;
}
carCharge = ChargeForCar(carType, numDays); // call to the function to calculate the charge
//for the rental car
taxTotal = (mileCharge + carCharge) * TAX;
grandTotal = mileCharge + carCharge + taxTotal;
}
string carSize(char carType) //function for setting car type name as a string type
{
string typeName;
if (carType == 'C')
{
typeName = "Compact size";
}
else if (carType == 'M')
{
typeName = "Mid size";
}
else if (carType == 'F')
{
typeName = "Full size";
}
else if (carType == 'S')
{
typeName = "SUV size";
}
return typeName;
}
void billOutput(string carTypeName, int numDays, double miles, double carCharge, double
milageCharge, double taxTotal, double grandTotal)
{
cout << "Rent2U Rental Details" << endl << endl;
cout << "Car Size: " << carTypeName << endl;
cout << "Days Rented" << numDays << "days" << endl;
cout << "Miles Driven" << miles << "miles" << endl << endl;
cout << "BILL" << endl;
cout << "Car Charge" << "$" << carCharge << endl;
cout << "Mialge Charge" << "$" << milageCharge << endl;
cout << "Tax" << "$" << taxTotal << endl;
cout << setw(21) << " " << setw(11) << setfill('-') << "-" << endl;
cout << setfill(' ') << "Total Bill" << "$" << grandTotal << endl << endl;
}
It's because your implementation of totalBill has a different signature (i.e. different parameters) from the declaration. One takes two doubles then a char and the other, one double then a char. They need to match.
Related
I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C++ so I'm still learning and this code is not completed yet but can anyone please help me with this?
int main()
{
// Declare Constant variables
const float DISC_GOLF_RETAIL = 14.96;
const float ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const float DISCOUNT2 = .16;
const float DISCOUNT3 = .24;
const float DISCOUNT4 = .32;
const double DEC = 100;
// Declare variables
double quantity;
double pricePerDisc;
double totalSavings;
double total;
char userInput;
float discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
// Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
// Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (discType)
{
case 1: userInput=='u' || 'U';
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
break;
case 2: userInput=='g' || 'G';
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
cout << "------------Receipt------------" << endl;
if (quantity>5 && quantity<=9)
{
discount = DISCOUNT1 / DEC;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>10 && quantity<=19)
{
discount = DISCOUNT2;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>20 && quantity<=29)
{
discount = DISCOUNT3;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>= 30)
{
discount = DISCOUNT4;
}
totalSavings = (pricePerDisc * quantity) * discount;
total = quantity * pricePerDisc - totalSavings;
cout << "Disc Type: " << discType << endl;
cout << "Quantity: " << quantity << endl;
cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
<< pricePerDisc << endl;
cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
<< totalSavings << endl;
cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
For single char responses, you can use the switch/case statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string is usually consists of more than one character.
I have an assignment here that I've been working on for the past few hours and have been met with a problem. Whenever I compile and run the program in VS Code it throws me into an infinite loop where the text of the "menu" is printed repeatedly. I imagine this has something to do with the for(;;){ loop at the beginning of the menu.
I've deleted the for(;;){ statement at the beginning of the menu, and the continuous scrolling stopped, but I was unable to input any numbers (cases) and the program, essentially, just printed the menu and that was the end.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
I suspect the problem resides in main(). I included the prior blocks of the program in case they were necessary to provide any suggestions.
You obviously want to read in "ch".
You've also made this an int, and don't zero-initialize, which can cause some undefined behaviour if you don't set it beforehand.
The switch case should be
switch(X){
case 1:
// Code
break;
}
etc..
The difference is "1" or 1. It evaluates an enumeration value, instead of strings.
For safety: you might want to add a case default, which is common practice.
This is a project from a c++ book I'm learning from.
I keep getting the error
"left of '.getDrinkPrice' must have class/struct/union"
I have tried fixing it but I just keep messing it up further. The visual studio error lists aren't too friendly for new users and this is really bothering me. I obviously don't want the code to be reposted fixed but I do want to be pointed in the right direction.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
double wallet = 10.00;
int change;
bool isRunning;
bool isChoosing;
int userChoice;
double pricePaid;
class Soda {
private:
string drinkName;
double drinkPrice;
int drinkAmt;
public:
Soda() {
drinkName;
drinkPrice = .75;
drinkAmt = 20;
}
void setDrinkName(string name) {
drinkName = name;
}
string getDrinkName() {
return drinkName;
}
void setDrinkPrice(double price) {
drinkPrice = price;
}
double getDrinkPrice() {
return drinkPrice;
}
void setDrinkAmt(int amt) {
drinkAmt = amt;
}
void setNewDrinkAmount(int amt, int i) {
drinkAmt = amt - i;
}
int getDrinkAmt() {
return drinkAmt;
}
};
// Declares classes
Soda * Cola = new Soda;
Soda * RootBeer = new Soda;
Soda * LemonLime = new Soda;
Soda * Grape = new Soda;
Soda * Cream = new Soda;
Soda *soda = new Soda;
static void init() {
// Pushes the Vending Machine data to the screen
cout << "Drink Name: " << " " << "Drink Cost: " << " " << "Number in machine: \n";
cout << *Cola->getDrinkName << " " << *Cola->getDrinkPrice << " " << *Cola->getDrinkAmt <<endl;
cout << *RootBeer->getDrinkName << " " << *RootBeer->getDrinkPrice << " " << *RootBeer->getDrinkAmt << endl;
cout << *LemonLime->getDrinkName << " " << *LemonLime->getDrinkPrice << " " << *LemonLime->getDrinkAmt << endl;
cout << *Grape->getDrinkName << " " << *Grape->getDrinkPrice << " " << *Grape->getDrinkAmt << endl;
cout << *Cream->getDrinkName << " " << *Cream->getDrinkPrice << " " << *Cream->getDrinkAmt << endl;
cout << endl;
cout << "You have $" << wallet << endl;
cout << endl;
}
void checkValidPurchase(Soda soda, double w, double p) {
double priceOfDrink = soda.getDrinkPrice();
int amountOfDrink = soda.getDrinkAmt;
// If there are enough drinks are in the machine
if (amountOfDrink > 0) {
// If user has enough money
if (w >= priceOfDrink) {
// If amount paid is greater than drink price
if (p > priceOfDrink) {
// Calculate price and change
w = w - p;
double getChange = p - priceOfDrink;
// Return Change
cout << "Paid " << p << " returning " << getChange << endl;
// Update amounts
int j = soda.getDrinkAmt;
soda.setNewDrinkAmount(j, 1);
w = w + getChange;
}
// If amount paid is equal to drink price
else if (p == priceOfDrink) {
// Calculate price
w = w - p;
cout << "Paid " << p << endl;
// Update amounts
int j = soda.getDrinkAmt;
soda.setNewDrinkAmount(j, 1);
}
// If amount paid is less than drink price
else if (p < priceOfDrink) {
// Prompt error and return to drink select
cout << "You did not enter enough money, returning to drink select. \n";
Sleep(3000);
}
}
// If user does not have enough money
else {
cout << "Not enough money in wallet. \n";
double amtNeeded = w + (w - priceOfDrink);
cout << "You have: " << w << " Needed for purchase: " << amtNeeded << endl;
Sleep(3000);
}
}
// If there are not enough drinks in machine
else {
cout << "Not enough of " << soda.getDrinkName << " in machine. \n";
Sleep(3000);
}
}
void sodaMachine() {
// Starts the drink select loop
isChoosing = true;
while (isChoosing) {
// gets user input
cout << "Enter the number of the soda you would like: \n";
cout << "Or to quit, press escape \n";
switch (userChoice) {
case 1:
cout << "Dispensing Cola \n";
cout << "Cost is .75 \n";
cin >> pricePaid;
checkValidPurchase(*Cola, wallet, pricePaid);
isChoosing = false;
break;
case 2:
cout << "Dispensing Root Beer \n";
cout << "Cost is .75 \n";
cin >> pricePaid;
checkValidPurchase(*RootBeer, wallet, pricePaid);
isChoosing = false;
break;
case 3:
cout << "Dispensing Lemon Lime \n";
cout << "Cost is .75 \n";
cin >> pricePaid;
checkValidPurchase(*LemonLime, wallet, pricePaid);
isChoosing = false;
break;
case 4:
cout << "Dispensing Grape \n";
cout << "Cost is .80 \n";
cin >> pricePaid;
checkValidPurchase(*Grape, wallet, pricePaid);
isChoosing = false;
break;
case 5:
cout << "Dispensing Cream \n";
cout << "Cost is .80 \n";
cin >> pricePaid;
checkValidPurchase(*Cream, wallet, pricePaid);
isChoosing = false;
break;
case WM_CHAR:
if (GetAsyncKeyState(VK_ESCAPE)) {
cout << "Exiting program \n";
isRunning = false;
break;
}
default:
isChoosing = false;
break;
}
}
}
int main() {
// Sets class values
Cola->setDrinkName("1. Cola");
RootBeer->setDrinkName("2. RootBeer");
LemonLime->setDrinkName("3. LemonLime");
Grape->setDrinkName("4. Grape");
Grape->setDrinkPrice(.80);
Cream->setDrinkName("5. Cream");
Cream->setDrinkPrice(.80);
isRunning = true;
while (isRunning) {
// Run Program
init();
sodaMachine();
system("cls");
}
return 0;
}
*Cola->getDrinkName is not correct.
Use either Cola->getDrinkName() or (*Cola).getDrinkName() instead; same for all other calls of the same kind in your code.
Okay so we have to change this program from reading input from a user to reading it off of a file, and so far i have changed a good chunk of the code that will read off of the file but every time i go to run the code i get these 5 errors that I can't figure out so here is my code
// Author:
// Source file:
// Description:
// Compiler used:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
struct records
{
int code;
double amount;
};
// Function Prototypes
void displayTitle();
double getBegBal(ifstream&);
void displayBal(records);
records getData(ifstream&);
double processCheck(double, double);
double processDeposit(double, double);
double processATM(double, double);
double processSvcChg(double);
//Global Constants
const double CHARGE = 10,
ATMFEE = 2;
int main()
{
//Variable Declarations
int transCode;
double balance,
transAmt;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
records trans;
ifstream inFile;
inFile.open("c:\\checkIn.dat");
displayTitle();
balance = getBegBal(inFile);
getData(inFile);
while (!inFile.eof())
{
trans = getData(inFile);
switch (trans.code)
{
case 1: balance = processCheck(balance, trans.amount); break;
case 2: balance = processDeposit(balance, trans.amount); break;
case 3: balance = processATM(balance, trans.amount); break;
}
displayBal(trans);
if (balance < 0)
balance = processSvcChg(balance);
getData(inFile);
}
return 0;
}
void displayTitle()
{
cout << "\n Check Register\n\n";
}
double getBegBal(ifstream& inFile)
{
//double bal;
records balance;
cout << " Enter beginning balance ";
inFile >> balance.amount;
return balance.amount;
}
void displayBal(records balance)
{
cout << "\t\tBalance = $" << setw(10) << balance.amount;
}
records getData(ifstream& inFile)
{
records rec;
cout << "\n\n Enter transaction code (0 to exit) ";
inFile >> rec.code;
if (rec.code > 0)
{
cout << "\n Enter transaction amount ";
}
return rec;
}
double processCheck(double bal, double amt)
{
cout << "\n Check = " << setw(10) << amt;
return (bal - amt);
}
double processDeposit(double bal, double amt)
{
cout << "\n Deposit = " << setw(10) << amt;
return (bal + amt);
}
double processATM(double bal, double amt)
{
records trans;
cout << "\n ATM = " << setw(10) << trans.amount;
bal = bal - amt;
displayBal(trans);
bal = bal - ATMFEE;
cout << "\n ATM Fee = " << setw(10) << ATMFEE;
return (bal);
}
double processSvcChg(double bal)
{
records trans;
cout << "\n Service chg =" << setw(8) << CHARGE;
bal = bal - CHARGE;
displayBal(trans);
return (bal);
}
error #2-3 are here
int transCode;
double balance,
transAmt;
the error is saying 'transCode': unreferenced local variable and
'transAmt': unreferenced local variable
errors #4-5 are here
double processATM(double bal, double amt)
{
records trans;
cout << "\n ATM = " << setw(10) << trans.amount;
bal = bal - amt;
displayBal(trans);// the error points here saying that the variable trans is uninitialized
bal = bal - ATMFEE;
cout << "\n ATM Fee = " << setw(10) << ATMFEE;
return (bal);
}
double processSvcChg(double bal)
{
records trans;
cout << "\n Service chg =" << setw(8) << CHARGE;
bal = bal - CHARGE;
displayBal(trans); // the error points here saying that the variable trans is uninitialized
return (bal);
}
Please and thank you for your help!
You initialized width = 0; and passed it to getWidth(). Therefore, width % 2 != 0 is evaluated as false and the prompt in getWidth() won't be displayed.
getWidth() won't need any arguments unless your assignment requires it because it is intended to just read the width and rethrn it.
do statement is useful to evaluate condition after executing loop body once.
int getWidth()
{
int width = 0;
do {
cout << "Enter width " << endl;
cin >> width;
} while (width % 2 != 0);
return width;
}
Then, use getWidth() in main() function like this:
width = getWidth();
It's working for me.
int displayMenu();
void displaySquare(int width);
void displayTriangle(int width);
int getWidth();
void displayUpsideDownTriangle(int width);
void displayDiamond(int width);
int main()
{
int width, shapes;
do {
shapes = displayMenu();
width = 0;
switch (shapes)
{
case 1:
width = getWidth();
displaySquare(width);
break;
case 2:
width = getWidth();
displayTriangle(width);
break;
case 3:
width = getWidth();
displayUpsideDownTriangle(width);
break;
case 4:
width = getWidth();
displayDiamond(width);
break;
case -9:
cout << "End of Program " << endl;
default:
cout << "Please choose one of the shapes..." << endl;
}
} while (shapes != -9);
system("pause");
return 0;
}
//this function sets up the display for the user
int displayMenu() {
int shapes;
cout << "\n~~ Shape Display menu ~~ " << endl << endl;
cout << " 1....Square\n" <<
" 2....Triangle\n " <<
" 3....Upside Down triangle\n " <<
" 4....Diamond\n\n " <<
" -9....Exit Program " << endl;
cout << endl;
cout << " Make a selection " << endl;
cin >> shapes;
return shapes;
}
int getWidth()
{
int width = 1;
do {
if (width % 2 != 0)
{
cout << "Enter width " << endl;
cin >> width;
}
else
{
cout << "Please enter odd number only. \nEnter width " << endl;
cin >> width;
}
} while (width % 2 == 0);
return width;
}
void displaySquare(int width)
{
int rows, columns;
for (rows = 0; rows < width; ++rows)
{
for (columns = 0; columns < width; ++columns)
{
cout << "# ";
}
cout << endl;
}
}
void displayTriangle(int width)
{
int rows, Spacing, ColHashtag;
for (rows = 1; rows < width; rows++) //controls the rows
{
for (Spacing = (width - rows); Spacing >= 1; Spacing--) // spaces out the rows to make an isoceles triangle
{
cout << " ";
}
for (ColHashtag = 1; ColHashtag <= (rows * 2) - 1; ColHashtag++) //controls the columns
{
cout << "#";
}
cout << endl;
}
}
void displayUpsideDownTriangle(int width)
{
int rows, Columns, spacing;
//sets up the rows for the top
for ((rows = width - 1); rows >= 1; rows--)
{
for (Columns = 1; Columns <= width - rows; Columns++) // sets up the columns
{
cout << " "; // spaces out the symbols to make an isoceles triangle
}
for (spacing = 1; spacing <= 2 * rows - 1; spacing++)
{
cout << "#";
}
cout << endl;
}
}
void displayDiamond(int width)
{
displayTriangle(width);
displayUpsideDownTriangle(width);
}
replace int main() and getWidth() with this
int main()
{
int width, shapes,wt;
do {
cout << "Enter width " << endl;
cin >> width;
wt=getWidth(width);
if(wt!=0)
{
shapes = displayMenu();
}
else
{
shapes=-9;
}
switch (shapes)
{
case 1:
displaySquare(wt);
break;
case 2:
displayTriangle(wt);
break;
case 3:
displayUpsideDownTriangle(wt);
break;
case 4:
displayDiamond(wt);
break;
case -9:
cout << "End of Program " << endl;
break;
default:
cout << "Please choose one of the shapes..." << endl;
}
} while (shapes != -9);
system("pause");
return 0;
}
int getWidth(int width)
{
while (width % 2 != 0) {
cout << "Enter width " << endl;
cin >> width;
}
return width;
}
I am writing a program that is like a guessing die and card game. It simulates the user rolling a die, and based on what they toll a card is generated that is equivalent to the amount of points they received in that round based. For example, rolling 1 has a card that says the user caught a big fish, and earned 20 points. The problem that I have is incrementing points and keeping a running total. The program only displays the die number rolled, as opposed to how many points were earned that round. It also does not print the correct final total. I have been tinkering with it for a few days, which leads me to believe I am making a simple mistake. Please help. My code is pasted below.
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<string>
using namespace std;
class Dice {
private:
public:
int dicevalue;
int rollDice() {
srand(time(NULL));
int dicevalue = rand() % 6 + 1;
return dicevalue;
}
};
class Points {
public:
int total;
int dicevalue;
int Points::getpoints(int dicevalue) {
switch (dicevalue) {
case 1:
cout << "\nYou rolled " << dicevalue << " \n" << endl;
cout << "Huge Fish \n";
total = 0 + 20;
break;
case 2:
cout << "\nYou rolled " << dicevalue << " \n" << endl;
cout << "Old shoe \n";
total = 0 + 5;
break;
case 3:
cout << "\nYou rolled " << dicevalue << " \n" << endl;
cout << "Little Fish\n";
total = 0 + 10;
break;
case 4:
cout << "\nYou rolled " << dicevalue << "\n" << endl;
cout << "Small prawn\n";
total = 0 + 7;
break;
case 5:
cout << "\nYou rolled " << dicevalue << "\n" << endl;
cout << "Shark\n";
total = 0 + 40;
break;
case 6:
cout << "\nYou rolled " << dicevalue << "\n" << endl;
cout << "Huge Catfish\n";
total = 0 + 30;
break;
}
return total;
}
int getPoints() {
return dicevalue;
}
};
class Game : public Points {
private:
Dice dice;
Points points;
public:
int Game::playgame() {
int choice, points_to_add;
total = 0;
points_to_add = 0;
int dicevalue = dice.rollDice();
total = total;
points_to_add = total + points.getpoints(dicevalue);
cout << "The value of total is: " << total << endl;
//total = total + points_to_add;
cout << "You earned:" << total << " points this round" << endl;
//system("pause");
return total;
}
/*
int getPoints() {
return total;
}
*/
};
int main() {
int choice;
int mytotal = 0, total, points_to_add = 0;
Game game;
do {
cout << "Welcome to Go Fish 2.0!" << endl;
game.playgame();
cout << "Would you like to play again?" << endl;
cout << "1 to play, 0 to exit: " << endl;
cin >> choice;
} while (choice == 1);
mytotal = points_to_add + game.playgame();
cout << "My Total game points are" << mytotal << endl;
system("pause");
return 0;
}