Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hey guys so I am writing some coursework and I am almost there, in my code I create a treasure chest and a bag for the player. When the Player is shown the items in the chest they are asked to keep the items which are then stored in there bag or discard the items.
While testing my code I have noticed that the item the player is being shown is not the one that then stores in the bag, almost like the bag is taking from an invisible stack. Then at the end when I call the players bag it still shows as empty as if no items where ever stored????
Please can someone tell me where I am going wrong and how I might resolve it???
These are the specific sections of code that is causing the bug:
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl;
return;
}
Here is the whole code:
// Loot Class v11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <vector>
#define LootNumber 14
using namespace std;
// the 3 arrays initialise the 3 stats of each item
string NameOption[] = { "Stone", "Leather Gloves", "Dragon Gauntlets", "Chair Leg", "Dragon Scale Helmet", "Pebble", "Rusted Breastplate", "Dragon Breastplate", "Empty Bottle", "Chainmail Trousers", "Dragon Skin Trousers", "Broken Stick", "Dagger", "Dragons Sword" };
int RarityOption[] = { 0, 1, 3, 0, 3, 0, 2, 3, 0, 2, 3, 1, 2, 3 };
bool SetOption[] = { 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 };
// this class is grouping Name, Rarity and Set. Resulting in every Loot object made, contains 3 variables
class Loot
{
public:
string Name;
int Rarity;
bool Set;
// constructor initialises each of the feilds
Loot(string N, int R, bool S)
{
Name = N;
Rarity = R;
Set = S;
}
// default constructor
Loot()
{
Name = "Empty";
Rarity = 0;
Set = false;
}
// Prints a randomly selected item of loot to the screen, used to check randomisation and that all loot variables print in the correct order
void PrintLoot()
{
int i = rand() % LootNumber;
Loot A(NameOption[i], RarityOption[i], SetOption[i]);
cout << "Loot item: " << A.Name << endl;
cout << "Rarity out of 3: " << A.Rarity << endl;
cout << "Part of set: " << A.Set << endl;
}
};
// enables the creation of a container to stack Loot items in
class TreasureChest
{
public:
stack<Loot> Chest;
// stacks 4 random items in the chest
TreasureChest()
{
int i = rand() % LootNumber;
int j = rand() % LootNumber;
int k = rand() % LootNumber;
int h = rand() % LootNumber;
Chest.push(Loot(NameOption[j], RarityOption[j], SetOption[j]));
Chest.push(Loot(NameOption[k], RarityOption[k], SetOption[k]));
Chest.push(Loot(NameOption[i], RarityOption[i], SetOption[i]));
Chest.push(Loot(NameOption[h], RarityOption[h], SetOption[h]));
}
// prints full contents of Treasure Chest to screen
void ShowFullChest()
{
int i;
for (i = 1; i < 5; i++)
{
cout << "Item: " << i << endl;
cout << "Name:" << TreasureChest().Chest.top().Name << endl;
cout << "Rarity out of 3: " << TreasureChest().Chest.top().Rarity << endl;
cout << "Part of a set: " << TreasureChest().Chest.top().Set << endl;
TreasureChest().Chest.pop();
}
}
};
// Creates container for player to store their chosen Loot items
class PlayerRuckSack
{
public:
Loot Rucksack[10];
// default constructor initialising each array
PlayerRuckSack()
{
for (int i = 0; i < 10; i++)
{
Rucksack[i] = { "Empty", 0, false };
}
};
// prints contents of a rucksack to the screen to allow the player to see what they have collected
void ShowRucksack()
{
for (int i = 0; i < 10; i++)
{
cout << Rucksack[i].Name << " " << Rucksack[i].Set << " " << Rucksack[i].Rarity << " " << endl;
}
}
// replaces an each array with items of Loot and prints when all arrays have been replaced
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
};
// For runing the game
class Game : public PlayerRuckSack
{
public:
string PlayerName;
TreasureChest A;
Game()
{
PlayerName = "User 1";
}
Game(string U)
{
PlayerName = U;
}
// intro message to start game
void StartGame()
{
cout << "Welcome to the Cave of Luck" << endl;
cout << "What is your name brave warrior" << endl;
cin >> PlayerName;
cout << PlayerName << " There are 3 Treasure Chests in this cave" << endl;
cout << "Treasure Chests contain many different items" << endl;
cout << "However it appears your bag is small and can only hold 10 items in total" << endl;
cout << "Choose wisley " << PlayerName << endl;
cout << "Good Luck!!" << endl;
cout << " " << endl;
cout << " " << endl;
}
//Gives player choise whether to keep or discard each loot item
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
// Prints the top of TreasureChest to the screen plus uses Playerchoise() after each item is shown
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
// informs player another chest is coming
void NextChest()
{
cout << "Your next chest contains: " << endl;
cout << " " << endl;
}
// Prints end Game message
void EndGame()
{
cout << " " << endl;
cout << " " << endl;
cout << "You have opened all the Chests, come back soon to the Cave of Treasures" << endl;
cout << " THANKYOU FOR PLAYING" << endl;
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl; //B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
return;
}
};
int main()
{
Game A;
//TreasureChest A;
PlayerRuckSack B;
//A.StartGame();
srand(time(NULL));
A.PrintTreasureChest();
for (int i = 0; i < 10; i++)
{
cout << B.Rucksack[i].Name << " " << B.Rucksack[i].Set << " " << B.Rucksack[i].Rarity << " " << endl;
}
//A.NextChest();
A.EndGame();
//TreasureChest A;
//PlayerRuckSack B;
//int dim = 10;
//int P = index(B.Rucksack, dim);
//B.Rucksack[P] = A.Chest.top();
//cout << "Item in your Bag " << B.Rucksack[P].Name << B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
//cout << P << endl;
return 0;
}
I know why nothing is stored in your Rucksack
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
Take a careful look at this line:
while (x[i].Name != "empty" && 0 && false && i < n)
&& 0 && false? Both 0 and false mean this is always false and the Rucksack will be reported as empty no matter what.
Then the code will fall out the bottom of index() without returning a value.
After that program behaviour is undefined because you use a return value that was not returned. Any craziness might come after that.
Fix that and come back with another question if you can't figure out your other problem.
It is currently a bit vague.
Related
In my program, I have a vector of structs, and I'm trying to iterate through the vector while accessing the properties of each struct. However, the way I'm trying to do this doesn't seem to work. The struct in question is called "person", and it has properties including "Name" and "PartyID", which are the ones I'm trying to access.
I read somewhere online you could do this using pointers to the iterator, so that's what I tried to do (*it.Name and *it.PartyID), but the program won't compile. What am I doing wrong? Here are the errors I'm getting (using G++ to compile the program):
And here is the code I've written:
// DelibDem.cpp : Defines the entry point for the application.
//
#include "DelibDem.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
//initializing variables
using namespace std;
bool continue_ = true;
string name = "";
string partyID = "";
int numD = 0;
int numR = 0;
int difference = 0;
int vectorSize = 0;
int newVectorSize = 0;
int vectorPos = 0;
int demPos = 0;
int repPos = 0;
struct person{
string Name;
string PartyID;
string equivalentName;
string equivalenceClass;
};
vector<person> Sample;
int main()
{
//user adds people to the vector
while (continue_ == true) {
string personName;
string personPartyID;
string answer;
person inputtedPerson;
cout << "Enter a person's name: ";
std::getline(cin, personName);
//cout << personName;
cout << "Enter the person's party ID (D or R): ";
std::getline(cin, personPartyID);
//cout << personPartyID;
if (personPartyID == "D") person inputtedPerson = { personName, personPartyID, "", "Republicans" };
else person inputtedPerson = { personName, personPartyID, "", "Democrats" };
Sample.at(vectorPos) = inputtedPerson;
//cout << "{{" << Sample.at(0).Name << ", " << Sample.at(0).PartyID << ", " << Sample.at(0).equivalentName << ", " << Sample.at(0).equivalenceClass << "}\n";
//for (int i = 1; i < Sample.size(); i++) {
// cout << ", {" << Sample.at(i).Name << ", " << Sample.at(i).PartyID << ", " << Sample.at(i).equivalentName << ", " << Sample.at(i).equivalenceClass << "}\n";
//}
//cout << "}";
vectorPos++;
cout << "Do you wish to add more people? (Y/N) ";
cin >> answer;
if (answer == "N") continue_ = false;
cin.ignore();
}
//The number of Democrats in the sample is stored in numD. The number of Republicans is stored in numR.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
//print the number of Democrats and Republicans
cout << numD;
cout << numR;
//determine if an equivalence relation exists
if (numD == numR) cout << "An equivalence relation is possible" << endl;
else {
cout << "An equivalence relation is not possible, because ";
if (numD > numR) {
cout << "There are " << numD - numR << " more Democrats than Republicans" << endl;
int difference = numD - numR;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Democrat do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it) //this is the part I'm asking about
{
if (*it.Name == specifiedName && *it.PartyID == "D") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Democrats in the sample. Please try again." << endl;
else difference--;
}
}
else {
cout << "There are " << numR - numD << " more Republicans than Democrats" << endl;
int difference = numR - numD;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Republican do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)
{
if (*it.Name == specifiedName && *it.PartyID == "R") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Republicans in the sample. Please try again." << endl;
else difference--;
}
}
cout << "The number of Democrats and Republicans is now equal and an equivalence relation is possible." << endl;
}
//print the properties of each element in the sample
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
//creating two vectors containing only the Democrats and Republicans, respectively
vector<person> Democrats;
vector<person> Republicans;
for (auto& element : Sample)
{
if (element.PartyID == "D") {
Democrats.at(demPos) = element;
demPos++;
}
else {
Republicans.at(repPos) = element;
repPos++;
}
}
//assigning each Democrat to a Republican and vice versa
for (int i = 0; i < Democrats.size(); i++)
{
Democrats.at(i).equivalentName = Republicans.at(i).Name;
}
for (int i = 0; i < Republicans.size(); i++)
{
Republicans.at(i).equivalentName = Democrats.at(i).Name;
}
return 0;
//printing the properties of each element in the sample again
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
}
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.
I know I am probably missing something obvious, but my code will only run the do loop in the main function once. After the selected function (with menu selection) is ran the program exits instead of restarting the loop. I am not sure what is wrong with my loop. Please Advise.
P.S. This program is written in C++
Here is the entire body of the program. All of the functions work with the exception of the do loop in the main function.
//It also includes functions to cancel a selection and to show all seats on the flight.
//These allow the predefined functions within the program to operate.
#include <iostream>
#include <string>
//This sets the namespace of the entire program to std
using namespace std;
//This creates a constant variable for the rows of seats on the flight.
const int rows = 13;
//This creates a constant variable for the seats in each row on the flight.
const int seats = 6;
//This line creates the array to store the seat assignments.
char flight[rows][seats];
//This function displays the seating chart for the flight
int display()
{
cout << "Displaying the current seating assignments for the flight." << endl;
cout << "The '*' symbol means the seat is available and 'X' means it is not." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int i=0; i < rows; i++)
{
cout << "Row " << i+1 << " ";
for(int j=0; j < seats; j++)
{
cout << flight[i][j] << " ";
}
cout << endl;
}
}
//This function allows the user to assign their seat.
int assign()
{
int type;
cout << "To begin making your seat assignment please select your ticket type." << endl;
cout << "1. First Class" << endl;
cout << "2. Business Class" << endl;
cout << "3. Economy Class" << endl;
cout << "Please select 1, 2, or 3 from the menu." << endl;
cin >> type;
int fcrow;
string fcseat;
if(type == 1)
{
cout << "You selected First Class" << endl;
cout << "Please review available First Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int f = 0; f < 2; f++)
{
cout << "Row " << f+1 << " ";
for(int g = 0; g < seats; g++)
{
cout << flight[f][g] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (1 or 2)" << endl;
cin >> fcrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> fcseat;
cout << "You selected Row " << fcrow << " Seat " << fcseat << endl;
int fcsi;
if(fcseat == "A")
{
fcsi = 0;
}
if(fcseat == "B")
{
fcsi = 1;
}
if(fcseat == "C")
{
fcsi = 2;
}
if(fcseat == "D")
{
fcsi = 3;
}
if(fcseat == "E")
{
fcsi = 4;
}
if(fcseat == "F")
{
fcsi = 5;
}
flight[fcrow-1][fcsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
int bcrow;
string bcseat;
if(type == 2)
{
cout << "You selected Business Class" << endl;
cout << "Please review available Business Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int h = 2; h < 7; h++)
{
cout << "Row " << h+1 << " ";
for(int k = 0; k < seats; k++)
{
cout << flight[h][k] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (3-7)" << endl;
cin >> bcrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> bcseat;
cout << "You selected Row " << bcrow << " Seat " << bcseat << endl;
int bcsi;
if(bcseat == "A")
{
bcsi = 0;
}
if(bcseat == "B")
{
bcsi = 1;
}
if(bcseat == "C")
{
bcsi = 2;
}
if(bcseat == "D")
{
bcsi = 3;
}
if(bcseat == "E")
{
bcsi = 4;
}
if(bcseat == "F")
{
bcsi = 5;
}
flight[bcrow-1][bcsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
int ecrow;
string ecseat;
if(type == 3)
{
cout << "You selected Economy Class" << endl;
cout << "Please review available Economy Class Seats." << endl;
cout << " A " << "B " << "C " << "D " << "E " << "F " << endl;
for(int l = 7; l < rows; l++)
{
cout << "Row " << l+1 << " ";
for(int m = 0; m < seats; m++)
{
cout << flight[l][m] << " ";
}
cout << endl;
}
cout << "Please enter in the desired row (8-13)" << endl;
cin >> ecrow;
cout << "Please enter in the desired seat (A-F)" << endl;
cin >> ecseat;
cout << "You selected Row " << ecrow << " Seat " << ecseat << endl;
int ecsi;
if(ecseat == "A")
{
ecsi = 0;
}
if(ecseat == "B")
{
ecsi = 1;
}
if(ecseat == "C")
{
ecsi = 2;
}
if(ecseat == "D")
{
ecsi = 3;
}
if(ecseat == "E")
{
ecsi = 4;
}
if(ecseat == "F")
{
ecsi = 5;
}
flight[ecrow-1][ecsi] = 'X';
cout << "Displaying Updated Flight Seating Chart" << endl;
return display();
}
if(type != 1 && type != 2 && type !=3)
{
cout << "Error" << endl;
cout << "The Ticket Type Selected does not exist." << endl;
cout << "Exiting Program" << endl;
cout << ". . . . . . . ." << endl;
exit(13);
return(13);
}
}
//This function allows the user to cancel their seat selection.
int cancel()
{
int canrow;
string canseat;
cout << "We are sorry you wish to cancel your seat assignment." << endl;
cout << "Please enter the row of your seat (1-13)." << endl;
cin >> canrow;
cout << "Please enter the seat letter (A-F)." << endl;
cin >> canseat;
cout << "You selected Row " << canrow << " Seat " << canseat << endl;
int canseati;
if(canseat == "A")
{
canseati = 0;
}
if(canseat == "B")
{
canseati = 1;
}
if(canseat == "C")
{
canseati = 2;
}
if(canseat == "D")
{
canseati = 3;
}
if(canseat == "E")
{
canseati = 4;
}
if(canseat == "F")
{
canseati = 5;
}
flight[canrow-1][canseati] = '*';
return display();
}
//This function allows the user to exit the program.
int close()
{
cout << "Exiting Program" << endl;
cout << ". . . . . . . ." << endl;
exit(11);
return(11);
}
//This starts the main program/menu used to run the functions.
int main()
{
int z = 0;
do
{
//These for loops fill the flight array with '*' to show all seats as empty.
for(int a = 0; a < rows; a++)
{
for(int b = 0; b < seats; b++)
{
flight[a][b] = '*';
}
}
z = z+1;
}while (z = 0);
//This creates the LCV and sets it equal to 0 to run the do loop.
int x = 0;
do
{
//These four lines explain what the program does to the user.
cout << "Welcome to Flight Seat Assigner" << endl;
cout << "This program will allow you to select an available seat for your flight" << endl;
cout << "based on the ticket type and available seats." << endl;
cout << "You also can cancel a seat assignment or display the seating chart." << endl;
//This line tells the user to pick a menu option.
cout << "Please select from the following menu to begin." << endl;
//These lines tell the user what the menu options are.
cout << "1. Display Flight Seating Assignments" << endl;
cout << "2. Select a Seat" << endl;
cout << "3. Cancel a Seating Assignment" << endl;
cout << "4. Exit Program" << endl;
//This creates a variable to store the user's menu selection.
int menu = 0;
//This stores the user's selected menu option.
cin >> menu;
//This if statement runs if the user selects the first menu option.
if(menu == 1)
{
//This line runs the display function.
return display();
}
//This if statement runs if the user selects the second menu option.
if(menu == 2)
{
//This line runs the assign funciton.
return assign();
}
//This if statement runs if the user selects the third menu option.
if(menu == 3)
{
//This line runs the cancel function.
return cancel();
}
//This if statement runs if the user selects the fourth menu option.
if(menu == 4)
{
//This line runs the close function.
return close();
}
//This else statement runs if the user enters a non-menu option.
else
{
//These lines explain the user's meu selection mistake and closes the program.
cout << "Error" << endl;
cout << "The option selected does not exist." << endl;
cout << "Please enter a number between 1-4 when using the menu." << endl;
cout << "Closing Program" << endl;
cout << ". . . . . . . ." << endl;
exit (12);
return(12);
}
//This while statement controls when the do loop runs.
}while (x = 0 && x != 0);
}
Here is the code just for the do-while loop in question.
do
{
//These four lines explain what the program does to the user.
cout << "Welcome to Flight Seat Assigner" << endl;
cout << "This program will allow you to select an available seat for your flight" << endl;
cout << "based on the ticket type and available seats." << endl;
cout << "You also can cancel a seat assignment or display the seating chart." << endl;
//This line tells the user to pick a menu option.
cout << "Please select from the following menu to begin." << endl;
//These lines tell the user what the menu options are.
cout << "1. Display Flight Seating Assignments" << endl;
cout << "2. Select a Seat" << endl;
cout << "3. Cancel a Seating Assignment" << endl;
cout << "4. Exit Program" << endl;
//This creates a variable to store the user's menu selection.
int menu = 0;
//This stores the user's selected menu option.
cin >> menu;
//This if statement runs if the user selects the first menu option.
if(menu == 1)
{
//This line runs the display function.
return display();
}
//This if statement runs if the user selects the second menu option.
if(menu == 2)
{
//This line runs the assign funciton.
return assign();
}
//This if statement runs if the user selects the third menu option.
if(menu == 3)
{
//This line runs the cancel function.
return cancel();
}
//This if statement runs if the user selects the fourth menu option.
if(menu == 4)
{
//This line runs the close function.
return close();
}
//This else statement runs if the user enters a non-menu option.
else
{
//These lines explain the user's meu selection mistake and closes the program.
cout << "Error" << endl;
cout << "The option selected does not exist." << endl;
cout << "Please enter a number between 1-4 when using the menu." << endl;
cout << "Closing Program" << endl;
cout << ". . . . . . . ." << endl;
exit (12);
return(12);
}
//This while statement controls when the do loop runs.
}while (x = 0 && x != 0);
Sorry the code is so long, but the program is almost finished. I just need to fix the loop not restarting as far as I can tell.
BessieTheCow's comment led me to the correct solution for the program. I changed the functions to void and removed the returns for the most part. Now the program works great. Thank you for all of your help everyone. It is much appreciated by this programming noob.
Im making a text store menu. I have a basic weapon class with a string for name and weapon sound, a bool for if you already own the item or not and a double for the price.
I'm trying to compare the double price in the class to the global variable p_balance (players balance) to
check if the player can afford the item
Here's the class
class Weapon
{
public:
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
name = "name";
sound = "sound";
owned = owned;
price = 0;
}
Weapon(string i_name, string i_sound, bool i_owned, double i_price)//Constructor
{
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
void displayItems();
{
cout << name << " - " << price << "g." << endl;
}
}
};
(i know i know i should switch Weapon Weapons[i] to Weapon weapons[i] to make my life easier)
And here's my most recent attempt at accessing it
while (p_balance < Weapons[0].getPrice()) // Not enough gold
{
cout << "Sorry, it seems you don't have enough gold." << endl;
goto MainMenu;
}
I had tried to make a method within the class to get the price but that didnt work out, but thats why its calling on a method that doesnt exist
I've also toyed around with if loops but the were getting messy and displaying more info than i liked
After the owner money check, i have it perform a ownership check and check if something equipped to that items slot, but when I used nested if statements it displayed the result of all of them even if the first if (price) was failed so I figured maybe a while statement?
I'm not looking for the answer cause I want to learn but last time I posted here I got some great hints that really helped me out and I'm hitting the point of frustration with this so I figured I'd ask for help!
EDIT:
I took what you guys said into account and went back to the pseudo.
I'm quite pleased with how it is now:
#include <iostream>
#include <string>
using namespace std;
int p_choice;
double p_balance = 125;
//Simple Weapon Class
class Weapon
{
public:
int slot;
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
slot = 0;
name = "name";
sound = "sound";
owned = owned;
price = 0;
}
Weapon(int i_slot, string i_name, string i_sound, bool i_owned, double i_price)//Constructor
{
slot = i_slot;
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
double* p_ptr;
p_ptr = &price;
void displayItems();
{
int x = 0;
cout << slot << " - " << name << " - " << price << "g." << endl;
}
}
};
int main()
{
int p_selection;
bool hasWeapon, offHand, inStore;
hasWeapon = false;
offHand = false;
inStore = true;
//Weapon Array
cout << "---------------------------------------------" << endl;
Weapon Weapons[6];
Weapons[0] = Weapon(1, "Great Sword of Greatening", "Tssng", false, 50);
Weapons[1] = Weapon(2, "Claw", "Thwack", false, 10);
Weapons[2] = Weapon(3, "Silent Pea-shooter", "Pew Pew", false, 15);
Weapons[3] = Weapon(4, "Loudening Silencer Attachment", "...", false, 5);
Weapons[4] = Weapon(5, "Tiger-Repelling Rock ", "Meooowraaarah", false, 25);
Weapons[5] = Weapon(6, "The Stick of Truth", "How do you kill that which has no life", false, 100);
cout << "---------------------------------------------" << endl;
cout << "Welcome to my store, traveller!" << endl;
cout << "How can I help you?" << endl;
//Menu
do
{
cout << "1. Buy" << endl;
cout << "2. Check Balance" << endl;
cout << "3. Exit" << endl;
cin >> p_choice;
if (p_choice == 1)
{
//Ask player which weapon the want to buy
cout << "Which item are you interested in?" << endl;
cout << "(Choose using 1-6)" << endl;
cin >> p_selection;
if (p_selection >= 1 && p_selection <= 6)
{
int i_choice = p_selection - 1;// Take one off the choice so it corresponds correctly to the object in the array
if (Weapons[i_choice].owned == false && p_balance >= Weapons[p_selection].price)// check if item is owned/can be bought
{
if (hasWeapon == false)// flip "Slot" flag
{
hasWeapon = true;
}
Weapons[i_choice].owned = true;// flip ownership flag
p_balance = p_balance - Weapons[i_choice].price; // update balance
cout << "Good eye, that's a fine item! Enjoy your " << Weapons[i_choice].name << endl;
}
else if (Weapons[i_choice].price > p_balance)
{
cout << "Seems you're a little short on gold..." << endl;
}
else if (Weapons[i_choice].owned == true)
{
cout << "Seems you don't know how to dual wield, why don't you pick something else." << endl;
}
}
}
// Check Balance
if (p_choice == 2)
{
cout << "Your balance is: " << p_balance << "g." << endl;
}
// Leave
if (p_choice == 3 && inStore == true)
{
cout << "Thanks for stopping by! Good luck out there!" << endl;
inStore = false;
}
else if (p_choice == 3 && hasWeapon == false)
{
cout << "You're gonna want a weapon out there, traveller" << endl;
}
} while (inStore == true);
//Scenario
bool scenario = true;
cout << "Inventory" << endl;
for (int x = 0; x < 6; x++)
{
if (Weapons[x].owned == true)
{
//convey slot
cout << "Press " << Weapons[x].slot << " to use your " << Weapons[x].name << endl;
cin >> p_choice;
}
}
do
{
for (int y = 0; y < 1; y++)
{
int use = p_choice - 1;
if (Weapons[use].owned == true)
{
cout << Weapons[use].sound << endl;
}
}
} while (scenario == true);
system("pause");
return 0;
}
Only issue is it plays the "sound" nonstop, that for loop was an attempt to have it run 1 time lol
Here's the final final product
#include <iostream>
#include <string>
using namespace std;
int p_choice;
double p_balance = 125;
//Simple Weapon Class
class Weapon
{
public:
int slot, durability;
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
slot = 0;
name = "name";
sound = "sound";
owned = owned;
price = 0;
durability = 0;
}
Weapon(int i_slot, string i_name, string i_sound, bool i_owned, double i_price, int i_durability)//Constructor
{
slot = i_slot;
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
durability = i_durability;
void displayItems();
{
int x = 0;
cout << slot << " - " << name << " - " << price << "g." << endl;
}
}
};
int main()
{
int p_selection;
bool hasWeapon, offHand, inStore;
hasWeapon = false;
offHand = false;
inStore = true;
//Weapon Array
cout << "---------------------------------------------" << endl;
cout << "For Sale:" << endl;
Weapon Weapons[6];
Weapons[0] = Weapon(1, "Great Sword of Greatening", "Tssng", false, 50, 25);
Weapons[1] = Weapon(2, "Claw", "Thwack", false, 10, 15);
Weapons[2] = Weapon(3, "Silent Pea-shooter", "Pew Pew", false, 15, 20);
Weapons[3] = Weapon(4, "Loudening Silencer Attachment", "...", false, 5, 5);
Weapons[4] = Weapon(5, "Tiger-Repelling Rock ", "Meooowraaarah", false, 25, 30);
Weapons[5] = Weapon(6, "The Stick of Truth", "How do you kill that which has no life", false, 100, 50);
cout << "---------------------------------------------" << endl;
cout << "Welcome to my store, traveller!" << endl;
cout << "How can I help you?" << endl;
//Menu
do
{
cout << "1. Buy" << endl;
cout << "2. Check Balance" << endl;
cout << "3. Exit" << endl;
cin >> p_choice;
if (p_choice == 1)
{
//Ask player which weapon the want to buy
cout << "Which item are you interested in?" << endl;
cout << "(Choose using 1-6)" << endl;
cin >> p_selection;
if (p_selection >= 1 && p_selection <= 6)
{
int i_choice = p_selection - 1;// Take one off the choice so it corresponds correctly to the object in the array
if (Weapons[i_choice].owned == false && p_balance >= Weapons[p_selection].price)// check if item is owned/can be bought
{
if (hasWeapon == false)// flip weapon flag
{
hasWeapon = true;
}
Weapons[i_choice].owned = true;// flip ownership flag
p_balance = p_balance - Weapons[i_choice].price; // update balance
cout << "Good eye, that's a fine item! Enjoy your " << Weapons[i_choice].name << endl;
}
else if (Weapons[i_choice].price > p_balance)
{
cout << "Seems you're a little short on gold..." << endl;
}
else if (Weapons[i_choice].owned == true)
{
cout << "Seems you don't know how to dual wield, why don't you pick something else." << endl;
cout << "(You already own this item)" << endl;
}
}
}
// Check Balance
if (p_choice == 2)
{
cout << "Your balance is: " << p_balance << "g." << endl;
}
// Leave
if (p_choice == 3 && inStore == true)
{
cout << "Thanks for stopping by! Good luck out there!" << endl;
inStore = false;
}
else if (p_choice == 3 && hasWeapon == false)
{
cout << "You're gonna want a weapon out there, traveller" << endl;
}
} while (inStore == true);
//Scenario
bool scenario, equipped;
int attack, equip, choose;
equipped = false;
scenario = true;
do
{
Equip:
cout << "----------------------------------------------------" << endl;
cout << " Inventory" << endl;
for (int x = 0; x < 6; x++)
{
if (Weapons[x].owned == true)
{
//convey slot and display equippable items
cout << Weapons[x].slot << " - " << Weapons[x].name << " - Uses Left: " << Weapons[x].durability << endl;
}
}
cout << "----------------------------------------------------" << endl;
cout << endl;
cout << "What would you like to equip? (Select using the given number + Enter)" << endl;
cout << "(Press 9 to quit)" << endl;
cin >> choose;
equip = choose - 1;
if (choose == 9)
{
scenario = false;
}
else if (Weapons[equip].owned == true)
{
int action;
cout << "You have equipped " << Weapons[equip].name << endl;
Action:
cout << "Press 1 and Enter to use." << endl;
cout << "Press 2 and Enter to equip a new item" << endl;
cout << "Press 3 and Enter to go home" << endl;
cin >> action;
if (Weapons[equip].durability <= 0)// cant use broken items
{
cout << "That item appears to have broken!" << endl;
}
else if (action == 1 && Weapons[equip].durability >= 0)// attack and durability check
{
cout << Weapons[equip].sound << endl;
cout << endl;
Weapons[equip].durability--;// durability decrement
goto Action;
}
else if (action == 2)// change equip
{
goto Equip;
}
else if (action == 3)// exit
{
scenario = false;
}
}
} while (scenario == true);
cout << endl;
cout << "I wish you a safe journey home, traveller." << endl;
system("pause");
return 0;
}
Thanks again for the guidance.
I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}