I think I have a memory leak? - c++

I am trying to do the Knight's Tour using dynamic arrays because the user will be able to implement their own board size, and where they want to start the knight at in the board.
However, before I changed everything to dynamic arrays, I was able to perform my code just find using static arrays, but now that I switched to dynamic arrays whenever my code executes, I get a memory leak I believe and the program crashes. I was wondering if my deconstructor is not working properly? Or if there is a different way I have to delete the dynamic array?
I am also wondering if there is a way to make this code a little more efficient, more exactly make the Move() function a little more efficient. Thanks.
#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
class Knight
{
private:
int Tracker = 1;
int BoardSize;
int **Board = new int*[BoardSize];
public:
Knight(int s)
{
BoardSize = s;
for (int i = 0; i <= s -1; i++)
{
Board[i] = new int[s];
}
for (int i = 0; i <= s - 1; i++)
{
for (int j = 0; j <= s - 1; j++)
{
Board[i][j] = 0;
}
}
}
~Knight()
{
for (int i = 0; i <= BoardSize - 1; i++)
{
delete[] Board[i];
}
delete[] Board;
}
void MarkUp(int &val)
{
val = Tracker;
Tracker++;
}
void MarkDown(int &val)
{
val = 0;
Tracker--;
}
bool PossibleMove(int &val)
{
if (val == 0)
return 1;
else
return 0;
}
void Display()
{
for (int k = 0; k < (BoardSize * 5) + 1; k++)
{
cout << "-";
}
cout << endl;
for (int i = 0; i <= BoardSize - 1; i++)
{
cout << "| ";
for (int j = 0; j <= BoardSize - 1; j++)
{
cout << setw(2) << setfill('0') << Board[i][j] << " | ";
}
cout << endl;
for (int k = 0; k < (BoardSize * 5) + 1; k++)
{
cout << "-";
}
cout << endl;
}
cout << endl << endl;
}
bool Move(int x, int y)
{
if (Tracker > (BoardSize * BoardSize))
{
return true;
}
if (PossibleMove(Board[x][y])) {
if ((x - 2 >= 0) && (y + 1 <= (BoardSize - 1)))
{
MarkUp(Board[x][y]);
if (Move(x - 2, y + 1))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x - 2 >= 0) && (y - 1 >= 0))
{
MarkUp(Board[x][y]);
if (Move(x - 2, y - 1))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x - 1 >= 0) && (y + 2 <= (BoardSize - 1)))
{
MarkUp(Board[x][y]);
if (Move(x - 1, y + 2))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x - 1 >= 0) && (y - 2 >= 0))
{
MarkUp(Board[x][y]);
if (Move(x - 1, y - 2))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x + 2 <= (BoardSize - 1)) && (y + 1 <= (BoardSize - 1)))
{
MarkUp(Board[x][y]);
if (Move(x + 2, y + 1))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x + 2 <= (BoardSize - 1)) && (y - 1 >= 0))
{
MarkUp(Board[x][y]);
if (Move(x + 2, y - 1))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x + 1 <= (BoardSize - 1)) && (y + 2 <= (BoardSize - 1)))
{
MarkUp(Board[x][y]);
if (Move(x + 1, y + 2))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
if ((x + 1 <= (BoardSize - 1)) && (y - 2 >= 0))
{
MarkUp(Board[x][y]);
if (Move(x + 1, y - 2))
{
return true;
}
else
{
MarkDown(Board[x][y]);
}
}
}
return false;
}
};
int main()
{
int size = 0;
int Row, Col;
int opt = 0;
do
{
cout << "Welcome to Knights Tour!" << endl;
cout << "1) Start the Tour." << endl;
cout << "2) Quit." << endl;
cin >> opt;
switch (opt)
{
case 1:
{
cout << "Enter board size:" << endl;
cin >> size;
Knight K1(size);
cout << "Enter Row:" << endl;
cin >> Row;
cout << "Enter Column: " << endl;
cin >> Col;
if (K1.Move(Row, Col))
{
cout << "\nOperation was Successful." << endl;
cout << "Possible Solution:" << endl;
K1.Display();
}
else
{
cout << "\nThat is not Possible." << endl;
}
cout << endl;
break;
}
case 2:
{
exit(0);
break;
}
default:
{
cout << "Not a Valid Option." << endl;
cout << "Try Again Please." << endl;
cout << endl;
break;
}
}
} while (opt != 2);
return 0;
}

This code does not work as you think it does:
int BoardSize;
int **Board = new int*[BoardSize];
The value of BoardSize is going to be whatever happens to be in the memory that gets allocated for it, so the new is going to try to allocate an unknowable size array.
Don't use hand coded dynamic arrays for this. Use std::vector; That's what it's for. In real life production code, you should almost never ever use dynamically allocated arrays. You'll use one of the standard containers.

As noted in the comments by multiple people, memory leaks do not cause crashes (generally).
The issue is that inside the constructor you assign values to the Board array elements. However, you never allocate memory for the Board array itself. I.e. when you do Board[i] = new int[s];, Board points to some random address. This is because the line int **Board = new int*[BoardSize]; is not executed before the constructor starts.
So the following should work:
class Knight {
private:
int BoardSize;
int **Board;
public:
Knight (int s) {
BoardSize = s;
Board = new int*[BoardSize];
// Remainder of code
}
};
However, I really suggest you use std::vector for this instead. Then you won't have to deal with memory (de)allocation at all. That could look as concise as the following:
#include <vector>
class Knight {
private:
int BoardSize;
std::vector<std::vector<int>> Board;
public:
Knight (int s) : BoardSize(s), Board(s, std::vector<int>(s, 0)) { }
};
Note that I initialized the class members directory in the member initializer list.

Related

Need assistance with a for loop in Tic Tac Toe game

My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.
#include <iostream>
#include <string>
#define GRID_SIZE 3
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void champion() {
const char *possiblities[8]{
"123"
"456"
"789"
"147"
"159"
"258"
"369"
"753"
};
for (int i = 0; i < 8; i++) {
bool winner = true;
char previous_pos = '0';
const char *possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - 1;
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if
(previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char) 'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
tictacToeMap();
playgame();
champion();
}
}
};
int main() {
TicTacToe tic;
tic.playgame();
return 0;
}
The problem is here:
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
You probably meant:
if (winner == true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
First, do what Max Meijer said, by replacing if(winner = true) with if(winner == true). But the program is still broken. The problem is that in your string array, you are not separating each string with a comma, so when my debugger hits const char *possible_moves, it ends up just assigning the entire array concatenated together. So just separate each string in the possibilities array with a comma, like so:
const char *possiblities[8]{
"123",
"456",
"789",
"147",
"159",
"258",
"369",
"753"
};

C++ tic tac toe game only wins with one combination

I want the program to print "You win" when any of the instances in the champion() function are given. It only shows a winner when "123" is inputted. Whenever three X's are displayed anywhere else the program continues. For instance if three X's are given diagonally the program will still continue. Novice programmer so any criticism is greatly appreciated.
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void computers_turn() {
while (true) {
int choice = (rand() % 9) + 1;
int row = choice / 3;
int col = choice % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'O';
break;
}
}
}
void champion() {
const char* possiblities[8] = {"123", "456", "789", "147",
"258", "369", "159", "753"};
for (int i = 0; i < 8; i++) {
char previous_pos = '0';
bool winner = true;
const char* possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - '1';
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if (previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner) {
puts("You win");
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
champion();
tictacToeMap();
playgame();
computers_turn();
}
}
};
int main() {
TicTacToe ticTacToe;
return 0;
}

How to fix: for loops not reading for a vector

School assignment for coding a cows and bulls game. Final scoring loops not working and I am not sure what the reason is.
I have tried renaming the vectors, changing iterators, changing where in the code the vectors are declared/initialized (still not sure exactly the difference)
//Get Number to Guess
if (numlen == 0) {
cout << "Enter the number to guess: ";
cin >> num;
cout << "Enter the number of digits in code: ";
cin >> numlen;
numstr = to_string(num);
if (numstr.length() < numlen) {
int diff = numlen - numstr.length();
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
numstr = addz + numstr;
}
num = stoi(numstr);
}
vector<int> numvct(numlen, 0);
max1 = 1;
for (l = 1; l < numlen; ++l) {
max1 = max1 * 10;
}
for (j = max1, k = 0; j >= 1, k < numlen; j = j / 10, ++k) {
int addval1 = num / j;
num = num - (addval1 * j);
numvct.at(k) = addval1;
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << numvct.at(r) << "-";
}
}
}
else {
//Fill vector to pick from
for (i = 0; i <= 9; ++i) {
pickvct.push_back(i);
}
//Pull to random number
vector<int> numvct(numlen);
for (k = 0; k < numlen; ++k) {
tempnum1 = rand() % (pickvct.size() - 1);
numvct.at(k) = pickvct.at(tempnum1);
pickvct.erase(pickvct.begin() + tempnum1);
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << r << "-";
}
}
}
//Get guess
do {
do {
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
if (guesslen < numlen) {
int diff = numlen - guesslen;
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
guessstr = addz + guessstr;
}
guess = stoi(guessstr);
guesssame = true;
}
if (guesslen == numlen) {
guesssame = false;
}
while (guesslen > numlen) {
cout << "You can only enter " << numlen << " digits." << endl;
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
}
for (s = 0; s < guesslen; ++s) {
for (t = s + 1; t < guesslen; ++t) {
if (guessstr.at(s) == guessstr.at(t)) {
guesssame = true;
}
else {
guesssame = false;
}
}
}
if (guesssame == true) {
cout << "Each number must be different." << endl;
guesssame = true;
}
} while (guesssame == true);
vector<int> guessvct(guesslen, 0);
max2 = 1;
for (m = 1; m < guesslen; ++m) {
max2 = max2 * 10;
}
for (n = max2, o = 0; n >= 1, o < guesslen; n = n / 10, ++o) {
addval2 = guess / n;
guess = guess - (addval2 * n);
guessvct.at(o) = addval2;
}
//Check the guess
for (p = 0; p < guesslen; ++p) {
guessdigit = guessvct.at(p);
cout << "Guess digit at " << p << ": " << guessdigit << endl;
for (q = 0; q < guesslen; ++q) {
numdigit = numvct.at(q);
cout << "Num digit at " << q << ": " << numdigit << endl;
if (numdigit == guessdigit && q == p) {
bulls = bulls + 1;
if (bulls == numlen) {
win = true;
break;
}
cout << bulls << " bulls" << endl;
}
else {
if (numdigit == guessdigit && q != p) {
cows = cows + 1;
cout << cows << " cows" << endl;
}
}
}
}
} while (win == false);
To make sure the loop was working right I added the cout statements but it is printing the first one only:
Enter guess: ####
Guess digit at 0: #
Program finished
//Get Number to Guess
if (numlen == 0) {
...
}
else {
//Fill vector to pick from
...
}
Within this if else block, you have the following two lines:
vector<int> numvct(numlen, 0);
and
vector<int> numvct(numlen);
These lines declare and initialize vectors which pass out of scope when the program leaves their respective if / else blocks. You use this vector numvct again later, though, so I assume you also declared and initialized it before any of the shown code, and it probably starts off empty. Because those two numvct vectors within the if / else block pass out of scope, all the work you do to them goes away aswell. That means that when you try to use numvct again later, you're working with the (presumably) empty one that you declared at the very beginning of the program.
Instead of redeclaring numvct, try just resizing it:
//vector<int> numvct(numlen);
numvct.resize(numlen);
and
//vector<int> numvct(numlen, 0);
numvct.resize(numlen, 0);
Also you might want to try cutting down on the number of variables you're using here, and try to declare them only within the code blocks where they are really needed. It will make it easier to keep track of what's going on.
Edit: I just want to add that I suggest resizing the vectors, as opposed to any other operation you could perform on a vector, because I don't really know what your exact intended use for them was. I ran your code with these changes, as well as with the addition of ~25 other variable declarations that you did not include in your post, and it did things that seemed reasonable i.e. allowed me to choose a number, guess its digits, print number of cows and bulls etc.

Strange behaviour of pointers in C++

#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.

why increment variable changing the value of the array when they have different names

Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).