I’m a newbie in C++ programming and I’m following this book called jumping into C++ by Alex Allain, there’s a tic-tac-toe exercise in the book and I’m having a hard time completing that exercise, so far what I’ve done is to prompt user to enter X or O value, which get stored in a 2d array, I want to track if for example char X appeared 3 times in the array, so far I use counter++ but it only increment once. below is the source of what I’ve done so far hopefully it will make my question much more clearer and let me know as well how I’m doing in terms of the way my codes look such as its structure and functions:
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
void display_array(char array[][3]);
void check_input(char array[][3], int input);
void check_winner(char array[][3]);
int check_x(char array[][3]);
int check_o(char array[][3]);
int _tmain(int argc, _TCHAR* argv[])
{
char array[3][3];
int counter = 0;
for(int row = 0; row < 3; row++){
cout << "\n";
for(int col = 0; col < 3; col++){
counter++;
array[row][col] = counter;
}
}
display_array(array);
system("PAUSE");
return 0;
}
void display_array(char array[][3]){
int position_input;
string symbol_input;
do{
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
cout << " [ ";
cout << array[i][j];
cout << " ] ";
}
cout << "\n";
}
cout << "Position: ";
cin >> position_input;
check_input(array, position_input);
}while(position_input != 0);
}
void check_input(char array[][3], int input)
{
char user_input = input;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(user_input == array[i][j])
{
cout << "array[" << i << "][" << j << "] replace with: ";
cin >> array[i][j];
}
}
}
check_winner(array);
}
void check_winner(char array[][3]){
cout << check_x(array);
if(check_x(array) == 3){
cout << check_x(array);
}
else if(check_o(array) == true){
cout << "o";
}
}
int check_x(char array[][3]){
int counter, x[3];
counter = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(array[i][j] == array[i][j]){
counter++;
}
x[i] = counter;
return x[i];
}
}
}
int check_o(char array[][3]){
int counter;
counter = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(array[i][j] == 'o'){
counter++;
return counter;
}else{
return counter;
}
}
}
}
You have a bunch of little problems but the most immediate one seems to be this kind of thing:
Regardless of whether the element tested is an ‘o’ or not you are going to return after one loop. Change it to something like this: