Simple dice game C++ Having trouble switching players - c++

Hello I'm currently taking C++, and I'm a beginner. We had a choice to choose a dice game for our program. I chose a game that has the following rules:
Choose a number and roll the dice. You score a point every time you roll that number. When you roll that number, you get another turn. When that number is not rolled, the turn is over. Mark the tally for each time you roll the number. First one to a certain score of 10 points wins.
I've been working on this for the past 2 days, and I'm so frustrated. Any help is greatly appreciated. We're using classes and constructors. My main issue is being able to go back and forth between the two players. I tried using a do while loop, but it didn't really help. Here's my code:
//Dice game
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
class Die
{
private:
int num;
public:
Die(); //Default constructor because it doesn't require arguments
void roll();
int getNum();
void gameRules();
};
class Players
{
private:
int player1Num;
int player2Num;
public:
void playerTurn();
};
void Die::gameRules()
{
cout << " ****Welocome to Madawi's Dice Game ****\n\n ";
cout << "Here are the rules:\n\n ";
cout << "This is a two player game, so grab a buddy!\n\n ";
cout << "\t1.)Please choose a number from 1-6\n\n ";
cout << "\t2.)Then roll the dice, if it lands on the number";
cout << "\tyou chose, you get a point and go again\n\n ";
cout << "\t3.)If you choose a number and it doesn't land on";
cout << "\tthe number you chose,you don't recieve a point, ";
cout << "\tand the second player goes\n\n ";
cout << "\t4.)The first person to get to 5 points first wins!\n\n ";
cout << "ENJOY!!! Let's begin:\n\n ";
}
Die::Die()
{
num = 1; //Initialize so that the values start at one
srand((unsigned)time(NULL));
}
void Die::roll()
{
num = rand()%6 + 1;
}
int Die::getNum()
{
return num;
}
void Players::playerTurn()
{
Die die1;
cout << "Hello player 1! Please choose a number from 1-6:\n";
cin >> player1Num;
cout << "You've chosen the number " << player1Num << endl;
die1.roll(); //rolls the dice
cout << die1.getNum() << endl; //displays number rolled
if (player1Num == die1.getNum())
{
cout << "Good job player 1! You got the same number\n ";
player1Points++; //Keeps track of player 1's score
if(player1Points == 5)
{
cout << "Congratulations player 1 you've won the game!\n";
cout << "Thanks for playing!\n ";
}
}
else
{
cout << "Sorry the numbers didn't match up\n ";
cout << "Player 2 its your turn\n ";
cout << "Player 2 please choose a number ";
cin >> player2Num;
cout << "You've chosen the number " << player2Num << endl;
die1.roll();
cout << die1.getNum() << endl;
if(player2Num == die1.getNum())
{
cout << "Good job player 2! You got the same number\n ";
player2Points++; //Keeps track of player 2's points
cout << "Player 2 its your turn again, please choose a number:\n ";
cin >> player2Num;
die1.roll();
cout << die1.getNum() << endl;
}
if(player2Points == 5)
{
cout << "Congratulations player 1 you've won the game!\n";
cout << "Thanks for playing!\n ";
}
}
}
int main()
{
Die dice1;
Players player1;
Players player2;
dice1.gameRules(); //Says the game rules
player1.playerTurn(); //Player makes a selection
return 0;
}

You need to change your architecture:
class Players
{
private:
int player1Num;
int player2Num;
public:
void playerTurn();
};
int main()
{
Die dice1;
Players player1;
Players player2;
//...
}
As defined above, you have 4 players. Each Players class has 2 player numbers.
Decide. Are you having a class containing all the players and controlling them or are you have a single player class and letting the main function control the players?

You should create helper function void makeTurn(int player); And use it to make move for any player. It should contain do-while loop with rolling and scoring.
Pseudocode:
function makeTurn(playerNumber):
display "Player " + playerNumber + "turn"
do
roll = rollDice();
if (roll == playersChoice[playerNumber])
display "You scored one point!"
playersPoints[playerNumber]++;
else
display "Sorry, you have failed :("
break //End the loop
while true //Do infinitely (till break)
end function
Also, I don't see a reason for the Players class. Use an array for containing player scores and choices, then you can easily extend it to more players. If you meant it to be an instance of player, then you should just have score and choice fields, and the player move should be the makeMove function from the code I presented to you before, just using local fields instead of playersChoice and playersPoints arrays.

Related

Too Many Arguments in C++

I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);

Program not randomly generating results

This is a board game created using C++. In order to win, one player must be able to reach the end of the board three times. But the problem is that it is the the first player who is entered into the board game that is always winning. I have a function setup so the that the simulated dice uses a random number-generator. How can I fix this issue?
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
#define SIZE 20 //EDITED: SIZE is Defined at 20 for the number of squares wanted for the board game. Makes is easier for change
//NOTE TO SELF: This is the revamped version. "EDITED" marks addition/change from 'assignment2_fixed.cpp
/**********************
* FUNCTION PROTOTYPES *
***********************/
void displayRules();
void action();
void firstRoll();
void showState();
int spinDie();
bool play();
bool winner();
int square[SIZE]; //For each square on the board, SIZE is Defined
const int loseTurn=1, switchPlace=2, goAgain=3, moveBack=4; //CONSTANT! Labels each action location for each square
int *location, *lastsq, *losTurn; //EDITED: Declared for dynamic allocation for location on board, last square of board, and lost turn
string *names; //EDITED: This is to hold the names of the players
int numPlayers = 0; //Holds the number of players
int turn; //EDITED: First players turn
/************
* FUNCTIONS *
*************/
void displayRules(){ //Displays the rules to the player once the game starts
cout << "Welcome to 3X" << endl;
cout << "The first player to go around the board three times wins!" <<endl;
cout << "The player with the lowest number goes first" << endl;
cout << "The players take turns until one player wins" << endl;
cout << "The players must move forward the number of spaces the die displays" << endl;
cout << "If the player lands on a square with an action, the player must perform that action, otherwise the next player goes" <<endl;
cout << endl << endl;
}
void action(){ //EDITED: This lists actions for each square
square[2] = goAgain;
square[4] = switchPlace;
square[6] = goAgain;
square[8] = loseTurn;
square[11] = goAgain;
square[14] = moveBack;
square[16] = switchPlace;
square[18] = loseTurn;
}
void firstRoll(){ //EDITED: Initializes for the first die roll
numPlayers = spinDie();
for(int i=0; i<numPlayers; i++)
location[i];
for(int i=0; i<numPlayers; i++)
lastsq[i];
for(int i=0; i<numPlayers; i++)
losTurn[i];
}
void showState(){
for(int i=0; i<numPlayers; i++){
cout << "Player " << names[i] << " is at location " << location[i] << endl;
}
for(int i=0; i<numPlayers; i++){
cout << names[i] << " lands on last space " << lastsq[i] << " times " << endl;
}
}
int spinDie(){ //For the dice. Number is generated randomly based on time
int x = rand()%6 +1 ;
cout<< " a "<< x<< " was rolled"<<endl;
return x;
}
bool play(){ //EDITED: Play function through squares
srand(time(0));
while(true){
if(losTurn[turn]){
losTurn[turn] = 0;//EDITED: Finds if player lost turn based on the value of 'turn'
turn = (turn) % numPlayers;
continue;
}
cout << "Turn: "<< names[turn] << endl;
int spot = spinDie(); //EDITED: Players spot on the board based on random number generator
cout << "Number on die : " << spot << endl;
location[turn] += spot;
if(location[turn] >= SIZE-1){
location[turn] -= SIZE;
lastsq[turn]++;
cout << names[turn] << " passes End!"<<endl;
if(winner())
return true;
}
switch(square[location[turn]]){
case goAgain:
cout<<"Action: Go again.\n";
showState();
break;
case loseTurn:
cout<<"Action: Lose turn.\n";
losTurn[turn] += 1;
break;
case switchPlace:
cout<<"Action: Switch places\n";
break;
case moveBack:
cout<<"Action: Move back 2 places.\n";
location[turn] -= 2;
break;
default:
cout<<"Action: None\n";
}
showState();
turn = (turn) % numPlayers;
}
return false;
}
bool winner(){ //Finds the winner who hits the end square three times
if(lastsq[turn] == 3){
cout<<"\n"<<names[turn]<<" WIN!\n";//Prints name of player with their turn
return true;
}
return false;
}
/***************
* MAIN PROGRAM *
****************/
int main(){
srand(time(0)); //Makes time based number in die random
displayRules(); //Diplays the rules first
cout << "Please type in the number of players between 1-6 : " << endl;
cin >> numPlayers;
while ((numPlayers < 1) || (numPlayers > 6)) //EDITED: Guard against any values outside of 1-6
{
cout << "ERROR: Enter a value from 1 - 6: ";
cin >> numPlayers;
}
names = new string[numPlayers]; //EDITED: Dynamically allocates array of string to hold names of players
location = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold locations of players
losTurn = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold lost turn of players
lastsq = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold count of each time player reach end square
for(int i=0; i<numPlayers; i++){
cout << "Enter name of player " << i+1 << " " << endl; //EDITED: To get name of each player starting with Player 1 (i+1)
cin >> names[i]; //EDITED: Gets names of players into the dynamically allocated strings
}
while(true){//EDITED: Continues the loop
if(play())//EDITED: If the "Play" function is true
break;//EDITED: Breaks once the winner is found
}
return 0;
}
Although your question is vague, I can give you some help to start you off. First off I'm going to show your code for the random factor on the dice.
int spinDie(){ //For the dice. Number is generated randomly based on time
int x = rand()%6 +1 ;
cout<< " a "<< x<< " was rolled"<<endl;
return x;
This code makes it so that the compiler will generate ANY number within an integer range. Then you divide that random number by 6 and find the remainder with the remainder operator (%). The +1 will add to the remainder if it is a factor of 6 such as 36. Your code is fine. The problem is that it is based off of time. The first one on the board probably gets similar or the same numbers each time and the second one does too. Which would explain the first one always winning. I'm assuming the first one gets similar or the same rolls every time because of your lack of explanation of the SPECIFIC problem. Hope this helped a little lol.

Changing a Second Value withing a Vector Object in C++

I'm quite new at C++, and am learning about vectors and all that fun stuff. I'm trying to figure out how I can have the user add a room on his selected floor. I have most of the problem done, but just that part I am having a hard time figuring out, any help would be appreciated! The main issue I think is at the function ReplaceFloor, but I have no idea how to make it in a way that the user selects Choice 4, then enters the floor that he wants a room to be added, and have that floor vector store one more room in it. Thank you for your help in advance! I tried to make it as best understandable as I could- sorry I'm quite new.
// Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Floor.h" // must include Floor header file
#include "Room.h" // must include Room header file
#include "AccessPoint.h" // must include AccessPoint header file
#include <vector>
#include <string>
using namespace std;
// functions that fills up all Floors
void fillFloor(vector<Floor>&);
void deletesFloor(vector<Floor>&);
void replaceFloor(vector<Floor>&);
// functions that fills up all Rooms
void fillRoom(vector<Room>&);
void deletesRoom(vector<Room>&);
// functions that fills up all Access Points
void fillAccessPoint(vector<AccessPoint>&);
void printFloorVector(const vector<Floor>&); // prints the information of all floors
void printRoomVector(const vector<Room>&); // prints the information of all Rooms
void printAccessPointVector(const vector<AccessPoint>&); // prints the information of all Access Points
// Variable Declaration
int roomNumber;
int accessPointNumber;
int floorID =0;
int roomID = 0;
int accessPointID =0;
int floorTotal;
// Check Floor Number To Add Room To
int floorForRoomAdd =0;
int main() {
// Declaring Variables
int exitCheck = 0; // Used to loop if the user wants to check for more than date range
int choice;
// Creating Vector for Class Floor
vector<Floor> Building;
vector<Room> Floor;
vector<AccessPoint> Room;
// Calling the functions
cout << "How Many Floors Does This Building Contain? ";
cin >> floorTotal;
cout << endl;
for (int i = 0; i < floorTotal; i++) { // Gathers total floors number + How many rooms for each floor
fillFloor(Building);
cout << "How Many Rooms Are On This Floor? : " ;
cin >> roomNumber;
cout << endl;
for (int b = 0; b < roomNumber; b++) { // Gathers total Room number + How many access points for each room
fillRoom(Floor);
cout << "How Many Access Points Are In This Room? : ";
cin >> accessPointNumber;
cout << endl;
for (int c = 0; c < accessPointNumber; c++) { // Gather total access points + Status of each access point
fillAccessPoint(Room);
}
}
}
cout << "##############################################################" << endl;
cout << "# Done Building #" << endl;
cout << "##############################################################" << endl << endl;
while (exitCheck <1) {
// TITLE
cout<<"\nNETWORK MONITORING ACCESS POINTS \n";
cout<<"----------------------------------";
cout<<"\n1 - Display Building Information"; // Check (Some minor issue)
cout<<"\n2 - Add a Floor"; // Check
cout<<"\n3 - Delete a Floor"; // Check
cout<<"\n4 - Add a Room";
cout<<"\n5 - Delete a Room";
cout<<"\n6 - Add a Network Access Point";
cout<<"\n7 - Delete a Network Access Point";
cout<<"\n8 - Toggle Access Point Status";
cout<<"\n9 - Change Access Point Date";
cout<<"\n0 - Exit"; // Check
cout<<"\n";
// Input
cout<<"\nChoice: ";
cin>> choice;
// Determine Choice
if (choice == 1) {
cout << "##############################################################" << endl;
cout << "# The status of the building is #" << endl;
cout << "##############################################################" << endl << endl;
printFloorVector(Building); // Prints end result
cout << endl;
printRoomVector(Floor); // Prints end result
cout << endl;
printAccessPointVector(Room); // Prints end result
cout << endl;
}
else if (choice == 2) { // Adds a floor
fillFloor(Building);
cout << "Floor Has Been Created!" ;
//cin >> roomNumber;
//cout << endl;
}
else if (choice == 3) { // Deletes a floor
deletesFloor(Building);
}
else if (choice == 4) { // Adds a room
cout << "What Floor Would You Like To Add A Room To?";
cin >> floorForRoomAdd;
cout << endl;
replaceFloor(Building); //code where floor has the room info
cout << "How Many Rooms Are On This Floor? : " ;
cin >> roomNumber;
cout << endl;
}
else if (choice == 5) { // Deletes a room
cout << "What Floor Is The Room That You Would Like To Have Deleted?";
//code where floor has the room info
deletesRoom(Floor);
}
else if (choice == 6) { // Adds an access point
cout << "How Many Access Points Are In This Room? : ";
cin >> accessPointNumber;
cout << endl;
}
else if (choice == 7) { // Deletes an access point
}
else if (choice == 8) { // Changes access point status
}
else if (choice == 9) { // Change access point date
}
else if (choice == 0) { // Exits
exitCheck = 2;
}
else {
cout<< "Input Not Valid. Please Provide A Valid Input";
}
}
// Display the Purpose and that Program has now ended
cout << "\nThe Purpose Of This Program Is To Create A Building Network " << endl;
cout << "Access Operation That Uses Vectors, Clas Callings, And Loops" << endl;
cout << "\nThe Program Has Now Ended\n" << endl;
return 0;
}// End Program
void fillFloor(vector<Floor>& newBuilding) {
floorID++;
cout << "----------------------"<< endl;
cout << "Floor Numer: "<< floorID << endl;
cout << "----------------------"<< endl;
Floor newFloor (floorID, roomNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newBuilding.push_back(newFloor); // adds a new object to the newBuilding vector
cout << endl;
}
// Deletes Floor
void deletesFloor(vector<Floor>& newBuilding) {
int deletedFloor;
cout << "Enter Floor Number To Delete It"<< endl;
cin >> deletedFloor;
cout << "Floor Numer: "<< deletedFloor << " Has Been Deleted!" << endl;
deletedFloor = deletedFloor - 1;
newBuilding.erase(newBuilding.begin()+deletedFloor);
}
// Replace Floor Info
void replaceFloor(vector<Floor>& newBuilding) {
for (unsigned int i = 0; i < newBuilding.size(); i++) {
if (newBuilding[i].getFloorID() == floorForRoomAdd) {
int changeRoomTotal = newBuilding[i].getRoomNumber;
newBuilding[i].getRoomNumber = changeRoomTotal + 1;
}
}
}
// Insert New Room
void insertRoom(vector<Room>& newFloor) {
roomID++;
cout << "What Floor Will This Room Be Added In?"<< endl;
cout << "Room Numer: "<< roomID << endl;
cout << "----------------------"<< endl;
Room newRoom (roomID, accessPointNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newFloor.insert(newFloor.begin()+3, newRoom);
cout << endl;
}
void fillRoom(vector<Room>& newFloor) {
roomID++;
cout << "----------------------"<< endl;
cout << "Room Numer: "<< roomID << endl;
cout << "----------------------"<< endl;
Room newRoom (roomID, accessPointNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newFloor.push_back(newRoom); // adds a new object to the newFloor vector
cout << endl;
}
// Deletes Room
void deletesRoom(vector<Room>& newFloor) {
int deletedRoom;
cout << "Enter Room Number To Delete It"<< endl;
cin >> deletedRoom;
cout << "Room Number: "<< deletedRoom << " Has Been Deleted!" << endl;
deletedRoom = deletedRoom - 1;
newFloor.erase(newFloor.begin()+deletedRoom);
}
void fillAccessPoint(vector<AccessPoint>& newRoom) {
bool accessPointStatus;
accessPointID++;
cout << "----------------------"<< endl;
cout << "Access Point Number: "<< accessPointID << endl;
cout << "----------------------"<< endl;
cout << "What Is The Status Of This Access Point : ";
cin >> accessPointStatus;
AccessPoint newAccessPoint (accessPointID, accessPointStatus); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newRoom.push_back(newAccessPoint); // adds a new object to the newFloor vector
cout << endl;
}
// This will display all of the building information
void printFloorVector(const vector<Floor>& newBuilding) {
cout << "The Building Has: " << floorTotal << " Floors" << endl;
unsigned int newBuildingSize = newBuilding.size();
for(unsigned int i = 0; i < newBuildingSize; i++) {
cout << "Floor ID: " << newBuilding[i].getFloorID() << endl;
cout << "Total Rooms: " << newBuilding[i].getRoomNumber() << endl;
}
}
void printRoomVector(const vector<Room>& newFloor) {
unsigned int newFloorSize = newFloor.size();
for(unsigned int a = 0; a < newFloorSize; a++) {
cout << "Room ID: " << newFloor[a].getRoomID() << endl;
cout << "Total Access Points: " << newFloor[a].getAccessPointNumber() << endl;
}
}
void printAccessPointVector(const vector<AccessPoint>& newRoom) {
unsigned int newRoomSize = newRoom.size();
for(unsigned int b = 0; b < newRoomSize; b++) {
cout << "Access Point Number: " << newRoom[b].getAccessPointID() << endl;
cout << "Access Point Status: " << newRoom[b].getAccessPointStatus() << endl;
cout << endl;
}
}
As far as I understand, you want to fix the replaceFloor function so that you can add one more room to a particular floor.
In the code, you correctly identify the position of the floor element inside the building vector using the line: if (newBuilding[i].getFloorID() == floorForRoomAdd)
In addition to the steps you have done, you also need to actually add the room to the floor vector. For that, you can access the floor vector as newBuilding[i] and then call newBuilding[i].push_back(newRoomObject) where newRoomObject contains all the information you have specified for the new floor to be added. This will result in the room to be added in the floor vector.
If I have misunderstood your query in any manner, please mention that so I may update my answer. One query which I have, but can't comment due to lack of reputation is, why have you used newFloor.insert(newFloor.begin()+3, newRoom); in the insert room function. The only reason for the +3 constant I can see is that you may be thinking that you are saying that the first two spots are taken up by floorID and room no. Even in that case, it should be +2. Also, even then, floorID and room no will most probably be two integers (or some number), whereas the rooms are objects. You cannot mix those types in an array. Please clarify.

Object is initializing to unwanted value

I have been working on a trivial assignment to get used to coding. I am designing an ATM machine and at the moment it is composed of 2 classes:
BankAccount.cpp
Constructor for different types of account
Only has balance as a member
Transaction.cpp
Performs a method on the BankAccount (i.e make deposit, make withdrawl & get balance)
Problem: BankAccount is automatically initialized to a balance of 10 which is undesired. So for example, if I made a checking account and chose to deposit $10, balance would print out $20.
//BankAccount.h
//This class will simply take in a bank account
//with a balance, other classes will use a bank account object
//such as saving/checkings and perform operations on the
//balance
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
class BankAccount {
private:
float balance;
public:
BankAccount ();
float getBalance ();
void makeDeposit ();
void makeWithdrawl ();
};
#endif
//BankAccount.cpp
#include "BankAccount.h"
#include <iostream> //remove once done *not to self
using namespace std; //remove once done *note to self
BankAccount::BankAccount() {
balance = 0.00;
}
float BankAccount::getBalance() {
return balance;
}
void BankAccount::makeDeposit() {
cout << "How much would you like to deposit: ";
float deposit_value;
cin >> deposit_value;
balance += deposit_value;
}
void BankAccount::makeWithdrawl() {
cout << "How much would you like to withdrawl: ";
float withdrawl_value;
cin >> withdrawl_value;
balance -= withdrawl_value;
}
//Transaction.h
#ifndef TRANSACTION_H
#define TRANSACTION_H
class Transaction {
private:
BankAccount m_bao;
public:
Transaction(BankAccount&);
void displayOptions();
void printReciept();
};
#endif
//Transaction.cpp
#include "BankAccount.h"
#include "Transaction.h"
#include <iostream>
using namespace std;
Transaction::Transaction(BankAccount& bao) {
m_bao = bao;
}
void Transaction::displayOptions() {
cout << "\nPlease make a choice\n\n";
cout << "1: Make Deposit\n";
cout << "2: Make Withdrawl\n";
cout << "3: Check Balance\n";
int choice;
cin >> choice;
switch (choice) {
case 1:
m_bao.makeDeposit();
break;
case 2:
m_bao.makeWithdrawl();
break;
case 3:
m_bao.getBalance();
break;
}
}
void Transaction::printReciept() {
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
}
int main () {
BankAccount checking;
Transaction q(checking);
q.displayOptions();
q.printReciept();
}
I am sure the answer is right in front of my eyes, but my brain is just fried right now. I will continue to look for the solutions and let you guys know if my problem has been solved yet.
[EDIT]
Alright, now I am trying to make it so that the customer can choose to perform transactions on either Checking or Savings account. Currently I got it looking like this in my main():
int main () {
BankAccount checking(0.00);
BankAccount savings(0.00);
Transaction c(checking);
Transaction s(savings);
for(int i = 0; i < 10 ; i++) {
cout << "Make an option" << endl;
cout << "1. Checking " << endl;
cout << "2. Savings" << endl;
int choice;
cin >> choice;
if (choice == 1) {
c.prompt();
c.printReciept();
}
else {
s.prompt();
s.printReciept();
}
}
}
It works fine, but I would like to make this process more OOP-alized, if that makes sense :)
One option I was trying to look into was making a prompt function which would belong to Transaction.cpp. This would do everything that is done in main, except initializing the objects of course.
Your problem is this line:
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
Which the compiler sees as:
cout << "Current balance is now: " << (m_bao.getBalance() + '\n');
'\n' is 10 as an int, so you get this:
cout << "Current balance is now: " << (m_bao.getBalance() + 10);
You probably meant to do this:
cout << "Current balance is now: " << m_bao.getBalance() << '\n';
Remember that in C++, + almost always means "add these two numbers".

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.