Repost- How to keep running total with switch case - c++

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

Related

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

gotoxy prints wrong in c++

I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.

BlackJack Application. All menu options work except for the first option to actually play the game

I wrote a Black jack application in C++ and for some reason, when I choose the first option to play a game, it doesn't play. All other menu options work. Any help would be appreciated.
#include <iostream>
#include <string>
#include <conio.h>
#include "Card.h"
#include <vector> // Stadard Template Library (STL)
using namespace std;
string showCards( vector<Card> cards);
short sumCardValues( vector<Card> cards);
int main()
{
short cash = 100;
cout << "Welcome to Kyle's BlackJack Extreme! " << endl;
cout << "\nYou are starting out with $ " << cash << endl;
cout << "\nPress any key to continue... ";
_getch();
short choice = 0;
do
{
system("cls");
cout << "Menu\n" << endl;
cout << "1) Play a hand" << endl;
cout << "2) Show current cash balance" << endl;
cout << "3) Exit" << endl;
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "\nPlaying a hand..." << endl;
break;
case 2:
cout << "\nYour current cash balance: $" << cash << endl;
break;
case 3:
cout << "\nThank you for playing Kyle's Extreme BlackJack! " << endl;
cout << "\nYour final cash position: $ " << cash << endl;
break;
default:
cout << "\nError. Please select from the menu. " << endl;
break;
}
cout << "\nPress any key to continue...";
_getch();
} while (choice != 3);
return 0;
}
/// Show the cards in the vector (resizable aray)
string showCards(vector<Card> cards)
{
string output = "";
for (Card c : cards)
{
output += c.toString() + " ";
}
return output;
}
/// Add up the total value of the cards
short sumCardValues(vector<Card> cards)
{
short total = 0;
for (Card c : cards)
{
total += c.getValue(); // total = total + c.getValue();
}
return total;
}
/// Play a single hand of BlackJack
void playHand(short &cash)
{
// create two ArrayLists that can hold Card objects
// an AAraylist is a seizable array
// in C++, the ArrayList is called a vector
vector<Card> dealerCards;
vector<Card> playerCards;
short dealerCardsTotal = 0;
short playerCardsTotal = 0;
// get be amount
short bet = 0;
cout << "\nEnter bet amount: ";
cin >> bet;
// create two cards for the dealer and show the first one
int number;
Card card1;
Card card2;
dealerCards.push_back(card1);
dealerCards.push_back(card2);
dealerCardsTotal = sumCardValues(dealerCards);
cout << "\nDealer is showing: " << dealerCards[0].toString() << endl;
// create two cards for the player and show them both
playerCards.push_back(Card()); // create the card and put it directly into the ArrayList (vector)
playerCards.push_back(Card());
playerCardsTotal = sumCardValues(playerCards);
cout << "\nHere are your cards: " << showCards(playerCards) << endl;
// give cards to the player until they stand ('S')
char answer = '?';
do
{
cout << "\nDo you want to hit or stand (H/S)? ";
cin.sync(); // flush the input stream (keyboard buffer) -- cin.ignore(100, '\n')
cin >> answer;
cin.sync();
if (toupper(answer) == 'H')
{
// give a card to the player
Card c;
cout << "\nYou were dealt this card: " << c.toString() << endl;
playerCards.push_back(c); // add card to Player's hand
// sum up the card values
playerCardsTotal = sumCardValues(playerCards);
// did the player bust?
if (playerCardsTotal > 21)
{
// do you have an Ace that can be dropped to a 1 value?
for (Card c : playerCards)
{
if (c.getValue() == 11)
{
cout << "\nYour total is " << playerCardsTotal << endl;
c.flipAceToOne();
cout << "However, you have an Ace that was converted to '1' value" << endl;
playerCardsTotal = sumCardValues(playerCards);
cout << "\nYour new total is " << playerCardsTotal << endl;
// if we are good now, break out of the loop. otherwise, keep looping and looking for Aces
if (playerCardsTotal <= 21)
break;
}
}
}
// show the cards and the total
cout << "\nHere are your cards: " << showCards(playerCards) << endl;
cout << "Your total is " << playerCardsTotal << endl;
// if busted, stop the loop
if (playerCardsTotal > 21)
answer = 'S';
}
} while (toupper(answer) != 'S');
// if player's cardTotal is more than 21, the player busted so take money away
if (playerCardsTotal > 21)
{
cout << "\nYou busted!" << endl;
cash = cash - bet;
}
else
{
// player stands so the dealer hits until 17 or greater
do
{
if (dealerCardsTotal < 17)
{
Card c;
cout << "\nDealer was dealt: " << c.toString() << endl;
dealerCards.push_back(c); // add the card to the dealer's hand
cout << "\nDealer cards: " << showCards(dealerCards) << endl;
dealerCardsTotal = sumCardValues(dealerCards);
cout << "Dealer total: " << dealerCardsTotal << endl;
}
} while (dealerCardsTotal < 17);
// show the cards for the dealer and the player
cout << "\nYour cards: " << showCards(playerCards) << " (" << playerCardsTotal << ")" << endl;
cout << "\nDealer cards: " << showCards(dealerCards) << "(" << dealerCardsTotal << ")" << endl;
// who wins?
if (dealerCardsTotal > 21)
{
cout << "\nDealer Busted!" << endl;
cash = cash + bet;
}
else if (dealerCardsTotal > playerCardsTotal)
{
cout << "\nDealer Wins." << endl;
cash = cash - bet;
}
else if (playerCardsTotal > dealerCardsTotal)
{
cout << "\nYou win!" << endl;
cash = cash + bet;
}
else
{
cout << "\nYour pushed the dealer (tie)." << endl;
}
}
// show the current cash position
cout << "\nYour current cash balance: $" << cash << endl;
}
Card.H
#pragma once
#include <ctime>
#include <stdlib.h>
#include <string>
using namespace std;
class Card
{
private:
// attributes
char suit;
char face;
short value;
static bool randomizerSeeded; // class-wide variable (one copy in memory is shared by all Card objects)
public:
// constructor and destructor
Card();
~Card();
// behaviors
string toString();
bool flipAceToOne();
// accessors and mutators
inline char getSuit() { return suit; }
inline char getFace() { return face; }
inline short getValue() { return value; }
};
Card.cpp
#include "Card.h"
bool Card::randomizerSeeded = false;
Card::Card()
{
// seed the randomizer only once for all card objects
if( !randomizerSeeded ) //if (randomizerSeeded == false)
{
srand(time(NULL));
randomizerSeeded = true;
}
short min = 3;
short max = 6;
suit = rand() % (max - min + 1) + min;
min = 2;
max = 14;
short number = rand() % (max - min + 1) + min;
if (number >= 2 && number <= 9)
{
value = number;
face = number + 48;
}
else if (number == 10)
{
value = number;
face = 'T';
}
else if (number == 11)
{
value = 10;
face = 'J';
}
else if (number == 12)
{
value = 10;
face = 'Q';
}
else if (number == 13)
{
value = 10;
face = 'K';
}
else if (number == 14)
{
value = 11;
face = 'A';
}
else
{
value = -1;
face = 'E';
}
}
Card::~Card()
{
}
string Card::toString()
{
string output = "";
output += suit;
output += face;
return output;
}
bool Card::flipAceToOne()
{
if (value == 11)
{
value = 1;
return true;
}
else
{
return false;
}
}
In the case to play a hand, you never call the playHand() function.
case 1:
cout << "\nPlaying a hand..." << endl;
break;
Adding this call will fix that issue.
playHand(cash)

C++ logic error

I got 158, 1000, and 140 for the money outputs while I played.
The original amount I put in was 100.
The total amount of money and the amount of money entered by the user aren't showing up correctly when ran.
Sometimes, the total and the amount entered displays correctly, it should be noted.
But not always, and that's a problem.
There is some logic error(s) I can't figure out. Help?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <stdlib.h>
using namespace std;
void switchStatementsCalculations (int &slot1, int &slot2, int &slot3, string cherries, string
oranges, string plums, string bells, string melons, string bars);
void calculateAmountEarnedByPlaying (double &money, int slot1, int slot2, int slot3,
double &total);
int main()
{
int slot1;
int slot2;
int slot3;
double money=0;
double total=0;
double amountOfMoneyEnterd=0;
int count;
string cherries = "cherries";
string oranges = "oranges";
string plums = "plums";
string bells = "bells";
string melons = "melons";
string bars = "bars";
string doAgain;
cout << "We are going to be playing a slot machine game today." << endl;
srand(time(0));
do
{
cout << "Please enter the amount of money you'd like to insert into the slot machine. We will pull the lever for you." << endl;
cin >> money;
cout << "You put in $" << money << endl;
slot1=rand()%6+1;
slot2=rand()%6+1;
slot3=rand()%6+1;
switchStatementsCalculations(slot1, slot2, slot3, cherries, oranges, plums, bells, melons, bars);
calculateAmountEarnedByPlaying(money, slot1, slot2, slot3, total);
amountOfMoneyEnterd=(amountOfMoneyEnterd+money);
cout << "Would you like to play again? Please type yes if so." << endl;
cin >> doAgain;
if(doAgain!= "yes")
{
cout << "The total amount of money you put in the slot machine is " << amountOfMoneyEnterd << endl;
cout << "The total amount of money you won is $" << total << endl;
}
}
while(doAgain=="yes");
system("Pause");
return 0;
}
void switchStatementsCalculations(int &slot1, int &slot2, int &slot3, string cherries, string
oranges, string plums, string bells, string melons, string bars)
{
switch (slot1)
{
case 1:
cout << "You got " << cherries << endl;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
switch (slot2)
{
case 1:
cout << "You got " << cherries << endl;
break;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
switch (slot3)
{
case 1:
cout << "You got " << cherries << endl;
break;
case 2:
cout << "You got " << oranges << endl;
break;
case 3:
cout << "You got " << plums << endl;
break;
case 4:
cout << "You got " << bells << endl;
break;
case 5:
cout << "You got " << melons << endl;
break;
case 6:
cout << "You got " << bars << endl;
}
}
void calculateAmountEarnedByPlaying(double &money, int slot1, int slot2, int slot3, double &total)
{
double won=0;
if(slot1==slot2 || slot1==slot3 || slot2==slot3)
{
cout << "Congratulations! You won." << endl;
won=(money * 2);
cout << "You won " << won << endl;
}
else if ((slot1==slot2 && slot1==slot3) || (slot2==slot1 && slot2==slot3) || (slot3==slot1 && slot3==slot2))
{
cout << "Congratulations! You won." << endl;
won=(money*3);
cout << "You won " << won << endl;
}
else
{
cout << "You didn't earn any money." << endl;
}
total=(total+won);
}
One mistake is this in your calculateAmountEarnedByPlaying function:
double won;
You did not initialize this variable, thus it contains an indeterminate value.
It is only set if you've won something, but not set if you didn't win. You then do this at the end of your function:
total = (total + won);
If won is not initialized, then total will also be set to an indeterminate value (or undefined behavior occurs).
The won variable should be initialized to 0:
double won = 0;
Most compilers give a warning if you access an uninitialized variable like this. Please check that you have your warnings on to detect these issues.
The other issue is that you forgot a break in your switch statements:
switch (slot1)
{
case 1:
cout << "You got " << cherries << endl; // no break statement
case 2:
cout << "You got " << oranges << endl;
break;
If slot1 is 1, it will print both sets of output for case 1 and case 2.
None of this would be necessary if you used arrays instead of 6 separate variables and 6 separate lines of output:
std::string slot_items[] = {"cherries", "oranges", "plums", "bells", "melons", "bars"};
//...
int slots[3];
//...
for (int i = 0; i < 3; ++i)
slots[i] = rand()%6+1;
//...
// inside the function...
//...
for (int i = 0; i < 3; ++i)
cout << "You got " << slot_items[slots[i]] << endl;
A two line for loop replaces 60 lines of switch and case statements.

Left of '.getDrinkPrice' must have class/struct/union

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.