c++ : Deck not showing first card - c++
I am actually trying to create a bluff game of cards in c++. When I call the function showAllCards the card at the of the deck ( Ace of Hearts ) does not show on output, the only way to show it is to add both deck structures in main body.And when program runs (without top card), dev generates some warnings too. What am I doing wrong?
Also can you please refer some improvements/changes in program.
Here is the code:
#include <iostream>
#include<Strings.h>
#include<cstdlib>
using namespace std;
struct link{
int data;
link *link;
};
struct deck
{
string suit[32];
string value[32];
}card;
struct cardsDeck{
string nxt[20];
string suitlist[4] = {"hearts","spades","clubs","diamonds"};
string vals[8] = {"ace","two","three","four","five","jack","queen","king"};
}cdeck;
class Game
{
private:
link *first;
public:
Game();
void check();
void mask();
void pass();
void enterCard();
void showAllCards();
void shuffle();
void rearrangeCards();
};
Game::Game(){
first=NULL;
}
void Game::rearrangeCards(){
short int x = 0, y = 0, z = 0;
while(x < 32)
{
card.suit[x] = cdeck.suitlist[y];
card.value[x] = cdeck.vals[z];
++x;
++z;
if(x % 8 == 0)
{
++y;
}
if(z % 8 == 0)
{
z = 0;
}
}
}
void Game::showAllCards(){
int x;
while(x < 32)
{
if(card.suit[x]!=card.suit[x-1]){
cout<<"\n";
}
cout << card.value[x] << " of " << card.suit[x] << "\n";
++x;
}
}
int main(){
Game game;
int op;
game.rearrangeCards();
cout<<"Welcome to Bluff Mashter 20/12/15::6:46\nEnter the Operation please:\n\n";
cin>>op;
while(op!=0){
switch(op){
case 1:
game.showAllCards();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
}
}
return 1;
}
and here are the warnings
20 63 E:\Projjects\mainbluuf.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
21 78 E:\Projjects\mainbluuf.cpp [Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
20 63 E:\Projjects\mainbluuf.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
21 78 E:\Projjects\mainbluuf.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
assuming your method is this:
void Game::showAllCards(){
int x = 0;
while(x < 32)
{
if(card.suit[x]!=card.suit[x-1]){
cout<<"\n";
}
cout << card.value[x] << " of " << card.suit[x] << "\n";
++x;
}
}
in your first iteration you're doing this: card.suit[0]!=card.suit[-1] which is wrong.
void Game::showAllCards(){
int x = 1;
while(x < 32)
{
if(card.suit[x]!=card.suit[x-1]){
cout<<"\n";
}
cout << card.value[x] << " of " << card.suit[x] << "\n";
++x;
}
}
I didn't test the code though, but I guess that fixes the issue.
Note: I set x to 1 that's the only change. Since you're new to C++ by default uninitialized variables can contain any unpredicted values which is stored in that memory address, so the good practice is to always initialize your variables.
Update:
Try this:
void Game::showAllCards(){
for(x = 0; x < 32; ++x)
{
cout << card.value[x] << " of " << card.suit[x] << "\n";
}
}
Update 2:
int main(){
Game game;
int op;
game.rearrangeCards();
cout<<"Welcome to Bluff Mashter 20/12/15::6:46\nEnter the Operation please:\n\n";
cin >> op;
while(op!=0){
switch(op){
case 1:
game.showAllCards();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
}
cin >> op;
}
return 0;
}
Update 3:
void Game::showAllCards(){
string lastSuit = "";
for(x = 0; x < 32; ++x)
{
if(lastSuit != card.suit[x])
cout << "\n";
cout << card.value[x] << " of " << card.suit[x] << "\n";
lastSuit = card.suit[x];
}
}
After some logical torture and tips from Boynux I figured out both prblems.
for(int j=0;j<32;j++){
cout<<card.value[j] << " of " << card.suit[j]<<"\n";
if(j==7 || j==15 || j==23 || j==31)
{
cout<<"\n";
}
}
Related
How to read txt files into an array that are stored into class variables? [duplicate]
This question already has answers here: Reading file into array of struct c++ (3 answers) C++ Reading text file with delimiter into struct array (2 answers) C++ Reading data from text file into array of structures (2 answers) How do I read data from a text file into an array of struct (1 answer) Reading data from a text file into an array of structs (1 answer) Closed 2 years ago. #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; class BasketballPlayer { public: void printBasketballPlayer() const; BasketballPlayer(); //Constructor with Parameters private: string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; }; class BasketballTeam { public: string name; void printBasketballTeam() const; bool findPlayer(string &); void editPlayer(bool&); BasketballTeam(); //Default Constructor void getName() { getline(cin, name); } private: //void BasketballPlayer(); string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; string myArray[16][11]; string PlayerName[15]; float myArray[15][11]; void Team() { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; } } } }; int main() { BasketballPlayer Play; string Search; bool isPlayerThere; char Change; BasketballTeam Team; cout << " Welcome to the Brooklyn Net's Stats and DataBase " << endl; cout << " These are the stats of our new SuperStar " << endl; Play.printBasketballPlayer(); cout << " < Would you Like to Update stats of the roster > --> Y or --> N " << endl; cin >> Change; cout << endl; if (Change == 'Y' || 'y') { Team.findPlayer(Search); Team.editPlayer(isPlayerThere); } else { Team.printBasketballTeam(); } Team.printBasketballTeam(); return 0; }//end main void BasketballPlayer::printBasketballPlayer() const { cout << "|| The players name || " << this->name; cout << endl; cout << "|| Minutes Per Game || " << this->MinutesPlayed; cout << endl; cout << "|| Turnovers Per Game || " << this->TurnOver; cout << endl; cout << "|| Points Per Game || " << this->PointPerGame; cout << endl; cout << "|| Rebounds Per Game || " << this->Rebounds; cout << endl; cout << "|| Asists Per Game || " << this->AST; cout << endl; cout << "|| Blocks Per Game || " << this->BLK; cout << endl; cout << "|| 3 Point % || " << this->ThreePointers; cout << endl; cout << "|| Free-Throw % || " << this->FreeThrow; cout << endl; cout << "|| Field Goal %|| " << this->FieldGoal; cout << endl; cout << "|| Steals % || " << this->Steals; cout << endl; cout << "|| Player Scoreing Effiencey Rating || " << this->PlayerScoreEffRating; cout << endl; } BasketballPlayer::BasketballPlayer() //Constructor with Parameters { name = "James Harden"; MinutesPlayed = 40.2f; TurnOver = 4.2f; PointPerGame = 24.1f; Rebounds = 8.1f; AST = 12.0f; BLK = 0.6f; ThreePointers = 37.9f; FreeThrow = 89.2f; FieldGoal = 48.2f; Steals = 1.1f; PlayerScoreEffRating = 1.561f; } void BasketballTeam::printBasketballTeam() const { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; cout << myArray[i]; cout << endl; } } } bool BasketballTeam::findPlayer(string&) { bool Finder = false; const char *name; switch (*name) { case 1: if(name == "Kevin_Durant") Finder = true; break; case 2: if (name == "Kyrie_Irving") Finder = true; break; case 3: if (name == "James_Harden") Finder = true; break; case 4: if (name == "Joe_Harris") Finder = true; break; case 5: if (name == "Jarrett_Allen") Finder = true; break; case 6: if (name == "Jeff_Green") Finder = true; break; case 7: if (name == "Taurean_Prince") Finder = true; break; case 8: if (name == "Timothe_Luwawu - Cabarrot") Finder = true; break; case 9: if (name == "Spencer_Dinwiddie") Finder = true; break; case 10: if (name == "DeAndre_Jordan") Finder = true; break; case 11: if (name == "Bruce_Brown_Jr.") Finder = true; break; case 12: if (name == "Landry_Shamet") Finder = true; break; case 13: if (name == "Chris_Chiozza") Finder = true; break; case 14: if (name == "Reggie_Perry") Finder = true; break; case 15: if (name == "Tyler_Johnson") Finder = true; break; default: cout << " Player not in Roster " << endl; break; } return Finder; } void BasketballTeam::editPlayer(bool &) { int editValue; BasketballTeam Team; bool isThere; ifstream file("JustData.txt"); if (file.is_open()) { string myArray[15]; for (int i = 0; i < 15; ++i) { file >> myArray[i]; } } if (isThere == true) { cout << " What would you like to edit? " << endl; cout << "[1] Mintues, [2] Turnover, [3] Points Per Game, [4] Rebounds Per Game, [5] Steals Per Game, [6] Free Throw %, [7] Assits Per Game, [8] Filed Goal %" << endl; cout << "[7] Assits Per Game, [8] Filed Goal %[9] 3P%, [10] Player Scoring Eff, [11] Blocks Per Game ---> "; cin >> editValue; switch (editValue) { case 1: MinutesPlayed = editValue; break; case 2: PlayerScoreEffRating = editValue; break; case 3: PointPerGame = editValue; break; case 4: Rebounds = editValue; break; case 5: Steals = editValue; break; case 6: FreeThrow = editValue; break; case 7: AST = editValue; break; case 8: FieldGoal = editValue; break; case 9: ThreePointers = editValue; break; case 10: PlayerScoreEffRating = editValue; break; case 11: BLK = editValue; break; default: break; } } } BasketballTeam::BasketballTeam() //Default Constructor { int j; int row; int col; j = 0; ifstream file("JustData.txt"); if (file.is_open()) { float PlayerArray[15][11]; for (int row = 0; row < 15; row++) { for (int col = 0; col < 11; col++) { file >> PlayerArray[row][col]; MinutesPlayed = PlayerArray[j][col]; TurnOver = PlayerArray[j][col]; Rebounds = PlayerArray[j][col]; PointPerGame = PlayerArray[j][col]; AST = PlayerArray[j][col]; BLK = PlayerArray[j][col]; ThreePointers = PlayerArray[j][col]; FreeThrow = PlayerArray[j][col]; FieldGoal = PlayerArray[j][col]; Steals = PlayerArray[j][col]; PlayerScoreEffRating = PlayerArray[j][col]; j++; } } } ifstream file2("JustNames.txt"); if (file2.is_open()) { string PlayerName[15]; for (int row = 0; row < 15; row++) { file >> PlayerName[row]; name = PlayerName[row]; } } }; JustData.txt 36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 JustNames.txt Kevin_Durant Kyrie_Irving James_Harden Joe_Harris Jarrett_Allen Jeff_Green Taurean_Prince Timothe_Luwawu-Cabarrot Spencer_Dinwiddie DeAndre_Jordan Bruce_Brown_Jr. Landry_Shamet Chris_Chiozza Reggie_Perry Tyler_Johnson TeamNoTitle.txt Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 Bruce_Brown_Jr.,17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 TeamFileNets.txt Player,MPG,TOV,RPG,APG,SPG,BPG,PPG,FG%,3P%,FT%,SC-EFF Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 "Bruce_Brown_Jr.",17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 I'm sure that I'm not understanding Classes. Trying to use fstream to hold data of players so that my classes and driver code can change those files then display data from stored data in classes. I have no syntax errors but code not running. Most likey because of me reading file into array wrong to get data into my classes from file and improper calling of classes in main function.
Stack Smashing Detected C++ in Card game
So im programming a poker game (because im bored) and just setting out the classes and testing it works as i go along and its working perfectly BUT suddenly i add some new code to have an actual deck instead of infinite random cards and i just get this error *** stack smashing detected ***: <unknown> terminated Aborted (core dumped) This is from a g++ compiler on mint 19.3 cinnamon I looked at other questions that are similar to mine but they seem to be about large amounts of data and i dont really see how thats in my program. If someone could help out or at least explain the error message that would be great -thanks / my code / #include <iostream> #include <stdlib.h> using namespace std; class Card{ public: static Card* deck; static int current; char house; char value; void setTo(Card c){ house = c.house; value = c.value; } void random(){ setTo(*(deck + current)); current++; } void print(){ switch (value){ case 11: cout << "jack"; break; case 12: cout << "queen"; break; case 13: cout << "king"; break; case 14: cout << "ace"; break; default: cout << (int)value; break; } cout << " of "; switch (house){ case 0: cout << "spades"; break; case 1: cout << "clubs"; break; case 2: cout << "hearts"; break; case 3: cout << "diamonds"; break; default: cout << "there has been an error, the house is invalid"; break; } cout << endl; } static void CreateDeck(){ Card cs[52]; deck = &cs[0]; int k; for(int i = 0;i<4;i++){ for(int j = 0;j<14;j++){ k = (i*13) + j; deck[k].house = i; deck[k].value = (j+1); } } } static void ShuffleDeck() int j,k; Card t; for(int i = 0;i<52;i++){ j = rand() % 52; k = rand() % 52; t.setTo(*(deck+j)); (*(deck+j)).setTo(*(deck+k)); (*(deck+k)).setTo(t); } } }; class Player{ public: int chips; Card* hand; string pName; void initialize(string n){ chips = 1000; pName = n; Card cs[2]; hand = &cs[0]; } void print(){ cout << "player: " << pName << endl; cout << " "; (*hand).print(); cout << " "; (*(hand +1)).print(); cout << " " << chips << " chips" << endl; cout << endl; } void deal(){ (*hand).random(); (*(hand+1)).random(); } }; class Game{ public: int pot; Card* deck; void initialize(){ pot = 0; Card c[5]; deck = &c[0]; } }; Card* Card::deck = NULL; int Card::current = 0; int main() { srand (time(NULL)); Card::CreateDeck(); Card::ShuffleDeck(); Card b[2]; b[0].random(); b[1].random(); b[0].print(); b[1].print(); cout << endl; return 0; }
Your problem is here in createDeck: Card cs[52]; deck = &cs[0]; You have deck point to a local variable in the function. When the function exits the variable goes out of scope, so attempting to dereference deck invokes undefined behavior. The simplest fix is to dynamically allocate an array using new: deck = new Card[52]; And have a cleanup routine to delete [] the memory. A better way would be to define it as a std::vector: class Card{ public: static std::vector<Card> deck; ... std::vector<Card> Card::deck(52); This gives you better control over the memory. You will however need to change any explicit pointer arithmetic and derefernce to array subscript notation (i.e *(deck + x) --> deck[x] since std::vector doesn't support these operators. Also in createDesk, you're going off the end of the array/vector here: for(int j = 0;j<14;j++){ You want one less: for(int j = 0;j<13;j++){
Variable changing value and unsure of why
So I'm still fairly new to c++ and programming in general, but I'd like to assume that I have a fairly good grasp of the concept and control flow (possibly lol). I'm currently creating a top down style game that allows the user to interact with the inventory of a chest. The problem that has me extremely confused is that I modify a variable but then it changes to something entirely different after "updating" the console. Interactive chest inventory displaying 10 gold After pressing s to update the console The gold amount in the chest is set to 10 in the chestLoot() function, but is then changed to a value of 303, which is the macro for the Healing potion. Why is the chest.gold value being changed to 303 after I set it to 10? Any help on this would be much appreciated. (Don't be too harsh, I'm still new to stack overflow and c++ as well as programming in general) Here is the code that handles the chest inventory as well as the loot that is generated: void chestLoot(int x) { switch (tutorial.chestIt) { case 0: chest.inventory[x] = WOODEN_SWORD_ID; break; case 1: chest.inventory[x] = GOLD_ID; chest.gold = 10; break; case 2: chest.inventory[x] = HEALING_POTION_ID; break; case 3: chest.inventory[x] = LEATHER_HELMET_ID; break; } tutorial.chestIt++; } void chestInventory() { bool endLoop = false; int x = 0; int selection = 0; int highlighted = 0; while (endLoop == false) { system("cls"); std::cout << "Chest:" << std::endl << std::endl; if (tutorial.gridChestOpened == false) updatePlayer(5); for (x = 0; x <= player.level + 3; x++) { if (tutorial.gridChestOpened == false) { chestLoot(x); } switch (chest.inventory[x]) { case WOODEN_SWORD_ID: std::cout << x + 1 << ". "; if (selection == x) { std::cout << "- "; highlighted = selection; } std::cout << "Wooden Sword"; break; case GOLD_ID: std::cout << x + 1 << ". "; if (selection == x) { std::cout << "- "; highlighted = selection; } std::cout << chest.gold << " Gold"; break; case HEALING_POTION_ID: std::cout << x + 1 << ". "; if (selection == x) { std::cout << "- "; highlighted = selection; } std::cout << "Healing Potion"; break; case LEATHER_HELMET_ID: std::cout << x + 1 << ". "; if (selection == x) { std::cout << "- "; highlighted = selection; } std::cout << "Leather Helmet"; break; case NULL: break; } std::cout << std::endl; } tutorial.gridChestOpened = true; switch (_getch()) { case 'w': --selection; if (selection < 0) selection = 0; if (chest.inventory[selection] == NULL) ++selection; break; case 's': ++selection; if (selection > tutorial.chestIt) selection = tutorial.chestIt; if (chest.inventory[selection] == NULL) --selection; break; case 'e': if (chest.inventory[highlighted] == 0) { std::cout << "There is nothing there"; break; } else if (chest.inventory[highlighted] == GOLD_ID) { player.gold = player.gold + chest.gold; chest.inventory[highlighted] = NULL; break; } else { for (int y = 1; y <= player.level + 9; y++) { if (player.inventory[y] == NULL) { player.inventory[y] = chest.inventory[highlighted]; chest.inventory[highlighted] = NULL; } } } break; case 27: endLoop = true; drawScreen(NULL); break; } } } Here are the global variables that are used in the function: struct Loot { int inventory[2]; int gold; }chest, pot; struct Entity { int position[2] = { 2, 2 }; int gold = 0; int health = 10; int level = 1; int totalXp = 0; int inventory[11]; int mainHand[2] = {/*location, item*/}; }player/*enemy*/; struct Grid { int grid[6][12] = { {1,1,1,1,1,1,1,1}, {1,0,0,0,0,0,0,1,1,1,1,1}, {1,0,0,0,0,2,0,1,0,0,3,1}, {1,0,2,0,0,0,0,1,0,0,0,1}, {1,0,0,0,0,2,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1,4,1} }; bool gridChestOpened = false; int chestIt = 0; }tutorial; // Item ID's #define WOODEN_SWORD_ID 301 #define GOLD_ID 302 #define HEALING_POTION_ID 303 #define LEATHER_HELMET_ID 304 Any tips on improving my code are much appreciated as well :) 2: Check HerePassing a variable from one function to another
Your problem is that the member inventory of Loot is not dimensioned properly. The only valid values for x in chest.invetory[x] are 0 and 1. Your code is however clearly writing to chest.inventory[2], for example when you call chestLoot(2). The memory in a struct is laid out sequentially, so chest.inventory[2] = HEALING_POTION_ID; will quietly overwrite the next 4 bytes after the chest.inventory[1] which is chest.gold;
Well, the inventory member of your "loot" struct is an array of ints of length 2. But you seem to be calling "chestLoot" with a value greater than 1. This is causing you to go off the end of your array and write to where "gold" should be.
Decimal to binary/hex using arrays
I'm having trouble with the hexadecimal part of my c++ program. When I use the switch for hexadecimal nothing returns. also for some reason my binary conversion has a leading 0 I cant seem to get rid of. #include "stdafx.h" #include <iostream> #include <iomanip> #include <array> using namespace std; void binary(int, int); void hex(int, int); int _tmain(int argc, _TCHAR* argv[]) { int numb, base; cout << "Enter a decimel number : "; cin >> numb; cout << "Enter a base you want number switched to: "; cin >> base; switch (base){ case 2: binary(numb, base); break; case 8: break; case 16: hex(numb, base); break; default: break; } } void binary(int numb, int base) { int bin[32] = { 0 }; int i = 0; do { bin[i] = numb%base; numb = numb / base; i++; } while (numb != 0); cout << "\n"; while (i >= 0){ cout << bin[i]; i--; } cout << endl << endl; } void hex(int numb, int base){ int i; int hex[10] = { 0 }; for (i=0; i > 10; i++){ hex[i] = numb%base; numb = numb / base; for (i; i > 0; i--) { if (hex[i] >= 10) { switch (hex[i]){ case 10: cout << "A"; break; case 11: cout << "B"; break; case 12: cout << "C"; break; case 13: cout << "D"; break; case 14: cout << "E"; break; case 15: cout << "F"; break; default: break; } } cout << hex[i]; } } cout << endl; }
binary The problem is after the first loop, i is one greater than the last index. Just for example, say you enter 1: the do...while loop is entered, the digit 1 is put in array index 0, then i is incremented to 1. Then, in the second loop, both indexes 1 and 0 are printed. You can solve this by decrementing i before entering this loop: i--; while (i >= 0){...} You should be doing something like that anyway, because if you ended up using all 32 digits, you would try to access bin[32] and the program may crash or output gibberish. hex The first loop's condition is infinite: for (i = 0; i >= 0; i++){...} It should be the same as your condition in binary: for (i = 0; numb != 0; i++){...} But you are not done yet because I've noticed you also have a bug in your printing: if (hex[i] >= 10) { switch (hex[i]) { case 10: cout << "A"; break; ... } } cout << hex[i]; If hex[i] is greater than or equal to 10, it gets printed twice, once as a hex letter and once as a decimal number. To solve this you could, for example, use continue instead of break in your switch (to skip the second print), or use else: if (hex[i] >= 10) { switch (hex[i]) { case 10: cout << "A"; break; ... } } else { cout << hex[i]; } You also need to make the same correction as in binary: // decrementing i before entering the loop // vvv for (i--; i >= 0; i--){...} Your revision is not correct, hex should not have a nested loop. It was fine before, just with the corrections I've pointed out.
class initialization in C++
I tried to initialize an array of a class then use a loop to change the data members in each of the objects. I'm not sure how to get the values to stick, because after I changed the values, I tried to print a random object out and it's just the default values and not the changed values. Any help would be appreciated, Thanks! #include <iostream> #include <string> #include <time.h> using namespace std; class card { private: int rank; int suit; //////////////////////////////////////////////////////////// public: ///////////////////////////////////////////////////////////// // default constructor with initialization list card(int userRank = (2,3,4,5,6) , int userSuit=15) :rank(userRank), suit(userSuit){} /////////////////////////////////////////////////////////// // function to validate user's rank choice. int cardcheckRank(int pRank){ while(pRank<2 || pRank>14) { cout << "Choose a playing card rank between 2-14, where 11=Jack, " "12=Queen, 13=King, 14=Ace"<<endl; cin >> pRank; } return pRank; } ///////////////////////////////////////////////////////////// // function to validate user's suit choice. int cardcheckSuit(int pSuit){ while(pSuit<15 || pSuit>18) { cout << "Choose a playing card suit " "between 15-18, where 15=Diamond, 16=Club, 17=Heart, 18=Spades."; cin >> pSuit; } return pSuit; } ////////////////////////////////////////////////////////////////// // functioin to get a card value from user. void storeCard(int pRank, int pSuit){ card(cardcheckRank(pRank),cardcheckSuit(pSuit) ); } ///////////////////////////////////////////////////////////////// // translates string faceRank(int translateRank){ switch (translateRank) { case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Jack"; case 12: return "Queen"; case 13: return "King"; case 14: return "Ace"; default: return "Invalid"; } } /////////////////////////////////////////////////////////// // translate integer suit value into a word. string faceSuit(int translateSuit){ switch (translateSuit){ case 15: return "Diamonds"; break; case 16: return "Clubs"; break; case 17: return "Hearts"; break; case 18: return "Spades"; break; default: return "Invalid"; } } /////////////////////////////////////////////////////// // Function to print the current card. void printCard(){ cout << "The rank of the card is "; cout << faceRank(rank); cout << " and the suit is " << faceSuit(suit) << "." << endl; } }; // End of card class. ////////////////////////////////////////////////////// // main function. int main() { srand (time(NULL)); // initialize random seed. card deck[52]; char choice = 'n'; int h = 0; // card number. for(int i = 15; i < 19; i++) { int y = i; for(int j =2; j < 15; j++) { int z = j; (deck [h]).storeCard(z,y); cout << "Card rank " << (deck [h]).faceRank(z); cout << ", suit " << (deck [h]).faceSuit(y) <<endl; ++h; } } do{ cout <<"Would user like to play?(y/n)"<<endl; cin >> choice; int ranNum = (rand()% 51 + 0); if(choice == 'y') { cout << "User: "; deck[7].printCard(); } } while(choice == 'y'); return 0; }
Values are not sticking because your storeCard function doesn't really store the card, it creates a new card object and throws it away. If you really want to express this by invoking the card constructor, then assign the constructed object to the current one: void storeCard(int pRank, int pSuit){ *this = card(cardcheckRank(pRank),cardcheckSuit(pSuit) ); } A more idiomatic approach would be for storeCard to directly modify the object's attributes, much like the constructor does: void storeCard(int pRank, int pSuit){ rank = cardcheckRank(pRank); suit = cardcheckSuit(pSuit); }