Really frustrating debug Error with C++ - c++

So I am trying to make a pretty basic TicTacToe in C++, and while I have no apparent syntax errors, I am having a lot of Debug errors of : "Unhandled exception at 0x0100142D in Cobra.exe: 0xC0000005: Access violation reading location 0xCCCCC359"
I feel like it is an obvious Error that I am just not processing but it;s definitely starting to grate my nerves. I'll label where the access error is... Right now it;s in my checkwin method but I feel like there is definitely more than one..
In my header I use a private char** board and a private int player.
#include "TicTacToe.h"
#include <iostream>
using namespace std;
int main()
{
int rowChosen,
colChosen;
TicTacToe newGame;
while(newGame.checkWin()==' ' && !newGame.fullBoard())
{
newGame.displayBoard();
do
{
cout << "Player " << newGame.getPlayer() << " choose a row and column.";
cin >> rowChosen >> colChosen;
newGame.setGame(rowChosen,colChosen);
}while(newGame.setGame(rowChosen,colChosen)==false);
newGame.makeMove(rowChosen, colChosen, newGame.getPlayer());
newGame.switchPlayer();
}
newGame.displayBoard();
if(newGame.checkWin()!=' ')
cout << "Player " << newGame.returnWinner() << " wins!";
else if(newGame.fullBoard()==true)
cout << "Cat's Game: This is a Draw!";
return 0;
}
TicTacToe::TicTacToe()
{
player = 1;
char blank = ' ';
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
board[row][col] = ' ';
}
void TicTacToe::setPlayer(int play)
{
player = play;
}
int TicTacToe::getPlayer()
{
return player;
}
void TicTacToe::switchPlayer()
{
if (player==1)
player++;
else
player--;
}
bool TicTacToe::setGame(int row, int col) //input validation
{
if (row >= 3 || row < 0)
return false;
if (col >= 3 || col < 0)
return false;
if (board[row][col] != ' ')
return false;
return true;
}
char TicTacToe::getBoard(int row, int col)
{
return board[row][col];
}
bool TicTacToe::fullBoard()
{
bool full = true;
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
{
full=false;
break;
}
}
return full;
}
void TicTacToe::makeMove(int r, int c, int player)
{
char ch;
if (player==1)
ch = 'X';
else
ch = 'O';
board[r][c] = ch;
}
char TicTacToe::checkWin()
{
char b = ' ';
for(int i=0; i<3; i++) //horizontal
{
if((board[i][1]==board[i][0]) && (board[i][1]==board[i][2])) //THIS IS ERROR
{
b=board[i][1];
}
}
for(int j=0; j<3; j++) //vertical
{
if( (board[1][j]==board[0][j]) && (board[1][j]==board[2][j]) )
b=board[1][j];
}
if((board[0][0]==board[1][1] && board[1][1]==board[2][2]) ||
(board[2][0]==board[1][1] && board[1][1]==board[0][2]))
b= board[1][1];
return b;
}
void TicTacToe::displayBoard()
{
for(int row=0;row<3;row++)
{
cout << "|-----|";
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
cout << "| ";
else
cout << "|" << board [row][col];
}
cout << "|" << endl;
cout << "|-----|";
}
}
int TicTacToe::returnWinner()
{
int winner = 0;
if(checkWin()=='X')
winner = 1;
else if(checkWin()=='O')
winner = 2;
return winner;
}
This is my header TicTacToe.h
class TicTacToe
{
private:
char board[3][3]; //there we go
int player;
public:
TicTacToe();
void setPlayer(int);
int getPlayer();
void switchPlayer();
bool setGame(int,int);
char getBoard(int,int);
bool fullBoard();
void makeMove(int,int,int);
char checkWin();
void displayBoard();
int returnWinner();
};

Assuming you've included all the code, you're missing something essential: the declaration of the class TicTacToe. Of course, there's a TicTacToe.h, so it could be (probably is) hiding in there. That would help.
That all said, I think Mat has it right -- you declare a local named board inside the ctor and initialize it. But that goes out of scope as soon as the ctor is finished, which means all that initialization disappears into the aether.. Assuming you define board in your class, then simply removing that char declaration might be all you need.
Now, here's general advice: if you get an access violation exception, it usually means that you have made a mistake about the scope of something you're referring to. Since the exception happens at a point where you're using board, the slice of the program containing the identified board is the place to look.

Related

I am having an issue with my AI trying to delete the card that it just played?

I am making a card game, Crazy Eights, I have everything done except I am having a problem with this AI. The AI needs to delete the card it just played from its card options. (Each player is dealt 5 cards, and if the card matches the suit, value, or an 8, it can play). SO far, the computer does play the correct card, it just doesn't remove the card so it can just keep playing and playing.
Main Function
#include <iostream>
#include <time.h>
#include "CCrazyEight.h"
#include "stdafx.h"
using namespace std;
void main()
{
// Calls Crazy eight and declares a variable, then runs the game
CCrazyEight E1;
E1.Menu();
}
CCard Header File
#pragma once
#include <iostream>
#include <time.h>
#include "stdafx.h"
using namespace std;
enum CardSuit { Hearts, Diamonds, Spades, Clubs };
class CCard
{
friend ostream & operator << (ostream &left, CCard right);
private:
int value;
CardSuit suit;
public:
// Constructor, sets default values to suit and value
CCard()
{
value = 1;
suit = Hearts;
}
// return thes value of the card
int GetValue()
{
return value;
}
// returns the suit of the card
CardSuit GetSuit()
{
return suit;
}
// Passes values to CDeck constructor, which then randomizes values for the cards
void InitCard(CardSuit s, int v)
{
suit = s;
if (v > 0 && v < 14)
{
value = v;
}
}
};
// outputs value and suit of the card
ostream & operator << (ostream &left, CCard right)
{
if (right.value < 11 && right.value > 1)
{
left << right.value;
}
else if (right.value == 1)
{
left << "Ace";
}
else if (right.value == 11)
{
left << "Jack";
}
else if (right.value == 12)
{
left << "Queen";
}
else if (right.value == 13)
{
left << "King";
}
left << " of ";
if (right.suit == Hearts)
{
left << "Hearts";
}
else if (right.suit == Diamonds)
{
left << "Diamonds";
}
else if (right.suit == Spades)
{
left << "Spades";
}
else if (right.suit == Clubs)
{
left << "Clubs";
}
return left;
}
CDeck Header File
#pragma once
#include <iostream>
#include "CCard.h"
#include <time.h>
using namespace std;
class CDeck
{
private:
CCard Deck[52];
int TopCard;
public:
// constructor
// randomizes the card numbers for suit and value
CDeck()
{
srand(time(NULL));
TopCard = 0;
for (int suit = 0; suit < 4; suit++)
{
for (int value = 1; value <= 13; value++)
{
Deck[((suit * 13) + value) - 1].InitCard((CardSuit)suit, value);
}
}
}
// shuffles the deck, completely randomizes the cards
void Shuffle()
{
TopCard = 0;
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 52; x++)
{
int SwapPosition = rand() % 52;
CCard temp;
temp = Deck[x];
Deck[x] = Deck[SwapPosition];
Deck[SwapPosition] = temp;
}
}
}
// Draw a card function that gives out a card when called for in crazy eight
CCard DrawCard()
{
if (TopCard > 51)
{
cout << "Deck is Empty." << endl;
}
else
{
return Deck[TopCard++];
}
}
};
CrazyEight header file
#pragma once
#include <iostream>
#include <time.h>
#include "CCard.h"
#include "CDeck.h"
#include "CPlayer.h"
using namespace std;
// Having an issue trying to get the computer to play something different
class CCrazyEight
{
private:
CDeck d1;
CCard c1;
int index;
CCard Topcard;
CPlayer Computer;
CPlayer Human;
public:
// constructor
// shuffles the deck to the played, and assigns the topcard to start the game
CCrazyEight()
{
d1.Shuffle();
c1 = d1.DrawCard();
Topcard = c1;
}
// plays the game, dealing cards to computer and human
void PlayGame()
{
cout << "Welcome to Crazy Eight!" << endl;
cout << "You get to go first!" << endl;
cout << endl;
for (int k = 0; k < 5; k++)
{
Computer.GetCard(d1.DrawCard());
Human.GetCard(d1.DrawCard());
}
}
// displays the topmost card
void TopCard()
{
cout << Topcard << endl;
}
// displays the cards for the human, and the options they can chose, and anything else they need about the game
void Menu()
{
PlayGame();
while (Human.NumCards() != 0 || Computer.NumCards() != 0)
{
cout << endl;
cout << "Top Card is: "; TopCard();
cout << endl;
cout << "You Have " << Human.NumCards() << " Cards Left." << endl;
cout << "Your play: " << endl;
cout << "0) Draw Card" << endl;
cout << Human << endl;
cin >> index;
if (index == 0)
{
Human.GetCard(d1.DrawCard());
Topcard = Topcard;
}
else if (index > 0 && index <= Human.NumCards())
{
Topcard = Human.CardPlayed(index, Topcard);
}
cout << endl;
Topcard = Computer.ComputerAI(Topcard);
cout << "Computer Played: " << Topcard << endl;
if (Computer.NumCards() > 0)
{
cout << "Computer has " << Computer.NumCards() << " Cards Left." << endl;
}
else
cout << "You Lose!" << endl;
}
}
};
CPlayer Header File
#pragma once
#include "CCard.h"
#include <time.h>
#include <iostream>
using namespace std;
class CPlayer
{
friend ostream & operator << (ostream &left, CPlayer right);
private:
CCard Hand[25];
CDeck d1;
int NumberOfCard;
bool Computer;
const int MaxHand = 26;
bool TopCard;
public:
// Constructor for the computer, sets computer to true
CPlayer(bool computer = true)
{
Computer = computer;
NumberOfCard = 0;
}
// Computers AI, checks and sees if they can play, if not then they draw until they can play, or they play a card that is playable******Easy mode**** Lol
CCard ComputerAI(CCard Topcard)
{
for (int i = 0; i < NumberOfCard; i++)
{
if (Hand[i].GetSuit() == Topcard.GetSuit() || Hand[i].GetValue() == 8 || Hand[i].GetValue() == Topcard.GetValue())
{
for (int i = 0; i < NumberOfCard; i++)
{
if (Topcard.GetSuit() == Hand[i].GetSuit() && Hand[i].GetValue() != 8)
{
NumberOfCard--;
return Hand[i];
}
}
for (int i = 0; i < NumberOfCard; i++)
{
if (Topcard.GetValue() == Hand[i].GetValue() && Hand[i].GetValue() != 8)
{
NumberOfCard--;
return Hand[i];
}
}
for (int i = 0; i < NumberOfCard; i++)
{
if (Hand[i].GetValue() == 8)
{
NumberOfCard--;
return Hand[i];
}
}
}
else
{
GetCard(d1.DrawCard());
}
}
}
// Is not the computer, sets computer to fasle. i.e. its the human
void Human()
{
Computer = false;
}
int NumCards()
{
return NumberOfCard;
}
// will hand out a card
bool GetCard(CCard NewCard)
{
if (NumberOfCard < MaxHand)
{
// Now is taking the card
Hand[NumberOfCard] = NewCard;
NumberOfCard++;
return true;
}
else
return false;
}
// subtracts the card that was played from the deck of the human user
CCard CardPlayed(int index, CCard Topcard)
{
if (CheckCard(index, Topcard) == true)
{
CCard TempTopcard = Hand[index - 1];
for (int i = index - 1; i <= NumberOfCard - 1; i++)
{
Hand[i] = Hand[i + 1];
}
NumberOfCard--;
return TempTopcard;
}
else
cout << "Not a valid Card." << endl;
return Topcard;
}
// checks the card and see's if it is playable or not
bool CheckCard(int index, CCard Topcard)
{
if (Hand[index - 1].GetSuit() == Topcard.GetSuit() || Hand[index - 1].GetValue() == 8 || Hand[index - 1].GetValue() == Topcard.GetValue())
{
return true;
}
else
return false;
}
};
// overloads the output to cout the card
ostream & operator << (ostream &left, CPlayer right)
{
for (int i = 0; i < right.NumberOfCard; i++)
{
left << i + 1 << ") " << right.Hand[i] << endl;
}
return left;
}

creating a tic tac toe code with a class but only for the board display and defining the player

Hi so i have just recently started learning c++ and any help would be appreciated in my problem.
I've been asked to create a piece of code for a game (chosen tic tac toe)
but its divided between two people.
my role is to create a class for only the displaying of the board and the choosing of player x or player o.
so far i have tried creating this c++ code but errors keep showing, anyone know how to correct this??
p.s in the game i class it as XsandOs.
#include <string>
#include <iostream>
using namespace std;
class XsandOs // Name of the class
{
public:
XsandOs();
void drawboard();
void printBoard();
void getMove(int move);
void choosePlayer(char player);
bool checkwinner(const char board[3][3], char symbol, int plays);
private:
const char board[3][3];
};
void XsandOs::drawboard // Develops the board
{
cout << "Let's play X's and O's\n" << "_________________________________\n\n"; //This prints a title declaring the name of the game
//This action uses an array to create the board, the user will choose the number to select where they want the character to go.
char board[3][3] =
{
{ '1', '2', '3', }; //This creates the top row
{'4', '5', '6', }; // This creates the middle row
{'7', '8', '9', }; // This creates the bottom row
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << board[i][j] << "";
}
cout << endl;
}
}
void XsandOs::choosePlayer(char player)
{
if (player == 'X')
Player = 'O';
elseif(player == 'O')
Player = 'X';
return(void);
}
int main()
{
draw();
while (1)
{
input();
draw();
choosePlayer();
}
system("pause");
return 0;
}
I've cleaned up some of the design issues and created methods for you. There is still work to be done, you can't expect us to do it for you. Good luck.
#include <string>
#include <iostream>
using namespace std;
class XsandOs // Name of the class
{
public:
XsandOs();
void draw();
void input();
int getMove(); // 1-9 or zero on error
void choosePlayer();
bool checkWinner(); // true means game over
private:
char board[3][3];
char player;
};
XsandOs::XsandOs()
{
// initialize the board
player = 'X'; // x goes first
for (int i = 0;i < 3;++i)
for (int j = 0;j < 3;++j)
board[i][j] = ' '; // blank means the spot is empty
}
void XsandOs::draw() // Develops the board
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
int XsandOs::getMove()
{
// ask for a move
// validate the move or get a new move
// TODO
}
void XsandOs::input()
{
// ask for a move
int move = 0;
while (!move) {
move = getMove();
}
// do the move and update the board
board[move-1] = player;
}
void XsandOs::choosePlayer()
{
if (player == 'X')
Player = 'O';
elseif(player == 'O')
Player = 'X';
}
bool XsandOs::checkWinner()
{
// TODO
// Check the board state and look for a winner.
return false;
}
int main()
{
XsandOs game;
bool gameOver = false;
game.draw();
while (!gameOver)
{
game.input();
game.draw();
game.checkWinner()
gameOver = game.choosePlayer();
}
system("pause");
return 0;
}

Tic Tac Toe C++ Check & Print Winner

have a problem with this coding, how to check and display the winner? I have tried to add it but turns into error due to the function checkWinner().
#include <iostream>
using namespace std;
void showBoard(void);
void playerInput(int p);
void checkWinner();
void nextPlayer(int);
int board[3][3]={{0,0,0},{0,0,0},{0,0,0}};
int main()
{
int r;
int c;
int player;
int winner;
int turns;
cout << "******* Tic Tac Toe Game *******" << endl;
showBoard();
nextPlayer(1);
checkWinner();
return 0;
}
Output board function:
void showBoard(void)
{
int r;
int c;
for(r=0; r<=2; r++)
{
for(c=0; c<=2; c++)
{
if( board [r][c]==0)
cout << "0 ";
else if (board [r][c]==1)
cout << "1 ";
else
cout << "2 ";
}
cout << endl;
}
}
This is the player input function:
void playerInput(int p)
{
int row;
int col;
if(p==1)
cout <<"You are player number 1 \n\n";
else
cout <<"You are player number 2 \n\n";
cout<<"Please enter your coordinate:";
cin>>row;
cout<<"\n";
cin>>col;
if(p==1)
board[--row][--col]=1;
if(p==2)
board[--row][--col]=2;
}
Heres the problem I'm facing now, how to make it display the winner?
void checkWinner()
{
int winner;
for (int i=0; i<=2; i++)
{
if(board[i][0]==board[i][1] && board[i][1]==board[i][2] && board[i][0]!=0)
{
winner=board[i][0];
}
}
for(int i=0; i<=2; i++)
{
if (board[0][i]==board[1][i] && board[1][i]==board[2][i] && board[0][i]!=0)
{
winner=board[0][i];
}
}
if(board[0][0]=board[1][1] && board[1][1]==board[2][2] && board[0][0]!=0)
{
winner=board[0][0];
}
if(board[0][2]=board[1][1] && board[1][1]==board[2][0] && board [0][2]!=0)
{
winner=board[0][2];
}
if(board[0][0]==board[0][1] && board[0][1]==board[0][2]&& board[0][2]==board[0][1]&& board[1][0]==board [1][1]&& board[1][1]==board [1][2]&& board[1][2]==board[2][0]&&board[2][0]==board [2][1]&& board[2][1]==board [2][2] && board [0][0]!=0)
{
winner=0;
}
}
void nextPlayer(int player)
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
The problem is the game is not ended but it still asking for the player to resume and it keep updating the value.
click below to see the problem I'm facing. Thanks!
Click to view my output, it doesn't end the game
Your code has a serious recursion problem. The function checkWinner() in main never gets called because the function nextPlayer(1); is infinitely recursive, since, it lacks a base case.
A recursive base case, is what causes a recursive function to stop its recursion.
Note that in your code:
void nextPlayer(int player)
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
once nextPlayer(1); is called from main, it never returns, because, it always enters into another call of its own nextPlayer(player); at the end of the function. For this you need a base case to stop this recursion at some point from happening.
Now, logically your base case should actually be, checking for a winner before proceeding to play, which is what is handled by the checkWinner() function.
But, the problem is that the checkWinner() function returns void which means nothing so, in its current state, we cannot use it as a base case.
However, if we redesign it to return something such as:
0 for play on
1 or 2 indicating a player has won
and lastly -1 indicating that the board is full and nobody won (a tie).
So, reforming the checkWinner() function as (I also corrected a few conditions so have a close look at the code):
int checkWinner()
{
int winner;
// any of the rows is same
for (int i=0; i<=2; i++)
{
if(board[i][0]==board[i][1] && board[i][1]==board[i][2] && board[i][0]!=0)
{
winner = board[i][0];
return winner;
}
}
// any of the columns is same
for(int i=0; i<=2; i++)
{
if (board[0][i]==board[1][i] && board[1][i]==board[2][i] && board[0][i]!=0)
{
winner = board[0][i];
return winner;
}
}
// 1st diagonal is same
if(board[0][0]==board[1][1] && board[1][1]==board[2][2] && board[0][0]!=0)
{
winner = board[0][0];
return winner;
}
// 2nd diagonal is same
if(board[0][2]==board[1][1] && board[1][1]==board[2][0] && board [0][2]!=0)
{
winner = board[0][2];
return winner;
}
// if we reached here nobody has won yet
// if any empty box on board then play on
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++)
{
if(board[i][j]==0)
{
winner = 0;
return winner;
}
}
}
winner = -1; // all boxes full and nobody won so A tie has occurred
return winner;
}
Now, that it can be used, we will use it in void nextPlayer(int player) function as:
void nextPlayer(int player)
{
int winner = checkWinner();
if( winner == 0) // play on
{
playerInput(player);
showBoard();
if(player==1)
player=2;
else
player=1;
nextPlayer(player);
}
else if(winner == -1)
{
cout<<"\nGame drawn!\n";
}
else
{
cout<<"\nPlayer "<<winner<<" wins!\n"<<endl;
}
}
Note that, the checkWinner() condition is checked before we start to do anything.
And now, the call to checkWinner() in the main function, which was unreachable anyways, is not needed and will now be done before proceeding at every step in void nextPlayer(int player):
#include <iostream>
using namespace std;
void showBoard(void);
void playerInput(int p);
int checkWinner();
void nextPlayer(int);
int board[3][3]={{0,0,0},{0,0,0},{0,0,0}};
int main()
{
int r;
int c;
int player;
int winner;
int turns;
cout << "******* Tic Tac Toe Game *******" << endl;
showBoard();
nextPlayer(1);
return 0;
}
The rest of the functions are correct and will remain the same.
At two points in your code, you have used = in your if statement. This leads to initialization instead of equality checking. You should use == instead of the =.
if (board[0][0] = board[1][1] && /** This should be a == for checking equality */
board[1][1] == board[2][2] &&
board[0][0] != 0)
{
winner=board[0][0];
}
if (board[0][2] = board[1][1] && /** This should be a == for checking equality */
board[1][1] == board[2][0] &&
board[0][2] != 0)
{
winner = board[0][2];
}

array of strings inside the object

I've got a problem with creating an array of strings inside the object. I don't know how to patch it around so I'm asking for help. Here lies the problem:
main.h:
#pragma once
#include <iostream>
#include <conio.h>
#include <string>
class tab2D {
protected:
int width;
int height;
string **sTab;
int **iTab;
public:
tab2D();
tab2D(int x, int y, char c);
~tab2D();
tab2D(tab2D&t);
};
class chess: public tab2D {
public:
chess(int x, int y);
~chess();
chess(chess&c);
void init();
bool ifMove();
void show();
};
class matrix: public tab2D {
public:
matrix(int x, int y);
~matrix();
matrix(matrix&m);
};
The compiler says: syntax error : missing ';' before '*' about the line
string **sTab;
I assume that I can't make the dynamic array of strings and it makes further problems with processing this array.. Can you help me? :)
*UPDATE 1*Thanks, I forgot to add line
using namespace std;
Now it works, but I've got another problem.
#include "main.h"
using namespace std;
////// Konstruktor, konstruktor kopiujący oraz destruktor //////
chess::chess(int x = 8, int y = 8) : tab2D(x, y, 'c') {
init();
};
chess::chess(chess&c) {
chess(c.width, c.height);
};
chess::~chess() {
};
////// Metody //////
////// Uzupełnianie kolorów pól oraz rozstawianie figur i pionków //////
void chess::init() {
/// kolory pól: 0 - biały, 1 - czarny///
int last = 0;
for(int i = 0; i < this->height; ++i) {
for(int j=0; j < this->width; ++j) {
if(last = 0) {
this->sTab[i][j] = "1";
last = 1;
}
else if(last = 1) {
this->sTab[i][j] = "0";
last = 0;
}
}
if(last = 0)
last = 1;
else if(last = 1)
last = 0;
};
/// rozstawienie pionków ///
for(int i = 0; i < this->width; ++i) {
sTab[1][i] = sTab[1][i] + "0";
sTab[6][i] = sTab[6][i] + "a";
};
};
////// Wyświetlenie szachownicy //////
void chess::show() {
for(int i = 0; i < (this->height + 1); ++i) {
for(int j=0; j < (this->width + 1); ++j) {
if(i == 0 && j == 0)
cout << " ";
else if (i != 0 && j == 0) {
switch (i) {
case 1:
cout << "A ";
break;
case 2:
cout << "B ";
break;
case 3:
cout << "C ";
break;
case 4:
cout << "D ";
break;
case 5:
cout << "E ";
break;
case 6:
cout << "F ";
break;
case 7:
cout << "G ";
break;
case 8:
cout << "H ";
break;
default:
break;
}
}
else if (i == 0 && j != 0) {
cout << j << " ";
}
else {
cout << this->sTab[i-1][j-1] << " ";
}
}
cout << endl;
};
};
When I run the program, there is a breakpoint in the line
this->sTab[i][j] = "0";
I assume there is something wrong with making the array of strings but I don't understand why exactly there is a breakpoint and can't debug it.
UPDATE 2
Here is the code for tab.cpp:
#include "main.h"
using namespace std;
////// Konstruktor domyślny, konstruktor, konstruktor kopiujący oraz destruktor //////
tab2D::tab2D() {
};
tab2D::tab2D(int x, int y, char c) {
this->width = x;
this->height = y;
if (c == 'm') {
this->iTab = new int*[this->width];
for(int i=0;i<this->height;++i)
this->iTab[i] = new int[this->width];
}
else if (c == 'c') {
this->sTab = new string*[this->width];
for(int i=0;i<this->height;++i)
this->sTab[i] = new string[this->width];
}
else {
}
};
tab2D::tab2D(tab2D&t) {
tab2D(t.width, t.height, 't');
};
tab2D::~tab2D() {
for(int i=0;i<height;++i)
delete [] iTab[i];
delete [] iTab;
for(int i=0;i<height;++i)
delete [] sTab[i];
delete [] sTab;
};
You need to qualify names from the standard library:
std::string **sTab;
^^^^^
If you're doing what I think you're doing and allocating things with new, then you should consider using std::vector to deal with the quagmire of memory management issues you're about to encounter. If you really want to juggle pointers yourself for some reason, don't forget the Rule of Three.
UPDATE Your new problem might be because the copy constructor is horribly broken:
chess::chess(chess&c) {
chess(c.width, c.height);
};
This creates and destroys a temporary object, but doesn't initialise the object being constructed, leaving it in an invalid state. You probably don't want to declare a copy-constructor at all, as long as the base class is correctly copyable. If you did need one, it should should be more like:
chess::chess(chess const & c) : // 'const' so constant objects can be copied
tab2D(c) // copy the base-class subobject
{
// do whatever else needs doing
}
Alternatively, the new problem might be due to errors in the tab2D constuctors which you haven't shown us. The best way to track it down is to step through the program with a debugger, checking that everything is correctly initialised before use.
UPDATE Probably, the runtime error is caused by allocating the wrong number of pointers. You want
iTab = new int*[height]; // Not width
and likewise for sTab.

C++ Pizza Order Program not sure why the errors are happening

I'm new at programming so I'm not really sure what the problem is. The errors I keep getting are in the AddTopping(string toppings). One is illegal reference to non-static member PizzaOrder::toppings . The other one is 'initializing' can not convert for " to std::string.
This is what I've got at the moment:
#include <iostream>
#include <string>
using namespace std;
class PizzaOrder
{
private:
static const int MAX_SIZE=1000;
int size;
string toppings[MAX_SIZE];
int num_toppings;
public:
static const string toppings_offered [4];
static const int DEFAULT_SIZE= 0;
static const int DEFAULT_TOPPINGS=0;
static const double topping_base_cost;
static const double base_price;
PizzaOrder ();
PizzaOrder (int size);
bool SetSize (int size);
int GetSize () {return size;}
static string AddTopping (string topping);
static int AddTopping (int n);
static double GetPrice ();
static string StringizeSize ();
static string GetToppings ();
static void DisplayPizza();
};
const double PizzaOrder :: topping_base_cost= .5;
const double PizzaOrder :: base_price= 5;
const string PizzaOrder ::toppings_offered[4]={"olives","bell peppers","onions","pepperoni"};
int main ()
{
PizzaOrder order;
char pizza_size;
int topping_choice;
short array_size = sizeof(order.toppings_offered)/sizeof(order.toppings_offered[0]);
cout << "Would you like a size [S]small , [M]medium, [L]large pizza or [Q]quit?" <<endl;
while ( pizza_size != 'Q' || pizza_size != 'q')
{
cin >> pizza_size;
if( pizza_size == 'S' || pizza_size == 's')
order.SetSize(0);
if(pizza_size == 'M' || pizza_size == 'm')
order.SetSize(1);
if(pizza_size == 'L' || pizza_size == 'l')
order.SetSize(2);
while (topping_choice !=0)
{
cout << "Current Pizza : " << order.StringizeSize () << order.GetToppings ();
cout <<"Select an item by number. (Enter 0 when done)" << endl;
for (int i=0; i< array_size-1; i++)
{
cout << (i+1) << ". " << order.toppings_offered[i]<< endl;
}
cout << "Selection?";
cin >>topping_choice;
order.AddTopping(topping_choice);
}
}
return 0;
}
PizzaOrder::PizzaOrder()
{
size=DEFAULT_SIZE;
num_toppings=DEFAULT_TOPPINGS;
}
PizzaOrder::PizzaOrder(int size)
{
if(!SetSize(size))
size=DEFAULT_SIZE;
}
bool PizzaOrder::SetSize(int size)
{
if (size != 0 || size !=1 || size !=2)
return false;
this -> size=size;
return true;
}
string PizzaOrder::AddTopping(string topping)
{
string temp_toppings[]={toppings};
short array_size = sizeof(temp_toppings)/sizeof(temp_toppings[0]);
num_toppings+1;
toppings[num_toppings];
for(int k=0; k<array_size-1; k++)
{
toppings[k]= num_toppings[k];
}
toppings[num_toppings]= topping;
}
int PizzaOrder::AddTopping(int n)
{
string temp_toppings[]={toppings};
short array_size = sizeof(temp_toppings)/sizeof(temp_toppings[0]);
num_toppings+1;
toppings[num_toppings];
for(int k=0; k<array_size-1; k++)
{
toppings[k]= num_toppings[k];
}
toppings[num_toppings]=toppings_offered[n];
}
double PizzaOrder ::GetPrice()
{
double price;
double multiplier;
if(size==0)
multiplier=1;
if(size==1)
multiplier=1.15;
if (size==2)
multiplier=1.25;
price= (base_price*multiplier)+(num_toppings*topping_base_cost);
return price;
}
string PizzaOrder::StringizeSize()
{
if(size==0)
return "small";
if(size==1)
return "medium";
if (size==2)
return "large";
}
string PizzaOrder::GetToppings()
{
string temp= "";
for(int x=0,x<num_toppings-1, x++)
temp+= "+ " + toppings[x];
return temp;
}
void PizzaOrder::DisplayPizza()
{
cout << StringizeSize ()<< GetTopping () << GetPrice ();
}
You have a bunch of static functions that shouldn't be static, including AddTopping. Read up on static.
I'm not absolutely sure which line you're getting the "initializing cannot convert from" error on (please provide complete error information, including line numbers, in future questions), but I'd wager it's that first line in the integer overload of AddTopping. I gather that you're trying to copy the contents of the current "toppings" array member (inaccessible to you because you've declared the function static -- which is probably the reason that the type information is missing in the error message) into a temp_toppings array. The line, as you've written it, is not valid C++. I suggest you Google "C++ copy array" and read the first link, which is a nice array tutorial on the augustcouncil.com Web site.
Even if you get rid of all mistakes, you have a infinite loop running with the very beginning condition in the while loop -
The intention of this loop is to break from the loop, I assume. But it never does so -
while ( pizza_size != 'Q' || pizza_size != 'q')
{
// .....
}
When pizza_size is equal to Q, with the || condition, the condition turns out to be true and an infinite loop. It should be -
pizza_size = 'Q' => false || true => true -> while loop continues
pizza_size = 'q' => true || false => true -> while loop continues
while ( (pizza_size != 'Q') && (pizza_size != 'q'))
{
// .....
}
Hope it helps at later stages.