Feb 19, 2013 at 6:20pm Feb 19, 2013 at 6:20pm UTC
Hello, Im writing this program for my CIS 251 class and cant figure out why it keeps crashing when i input the x's and o's. my teacher wants us to input it all at once, like x.oxo.x.o or like this
x.o
.ox
ox.
If anyone can give me ideas id appreciate it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
#include <iostream>
using namespace std;
void input (char board [3][3]);
void print (char board [3][3]);
bool findWinner (char board [3][3], char player);
int main()
{
char board[3][3];
char yOrn;
while (true ){
cout << "Enter your board as characters (x, o or .): " << endl;
input(board);
cout << endl;
cout << "The board is: " << endl;
print(board);
cout << endl;
if (findWinner(board,'x' )){
cout << "X wins!" << endl;
}else if (findWinner(board,'o' )){
cout << "O wins!" << endl;
}else {
cout << "No winner!" << endl;
}
cout << endl;
cout << "Would you like to do another (y or n)? " ;
cin >> yOrn;
if (yOrn == 'n' ){
break ;
}
cout << endl;
}
return 0;
}
void input (char board [3][3]){
int i,j;
char * line;
for (i = 0 ; i < 3 ; i++){
cin >> line;
for (j = 0 ; j < 3 ; j++){
board[i][j] = line[j];
}
}
}
void print (char board [3][3])
{
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
cout << board[i][j];
if (j<2)
cout << " | " ;
}
cout << endl;
if (i<2){
cout << "_ _ _ _ _" << endl;
}
}
}
bool findWinner (char board [3][3], char player)
{
// Loop through each row
for (int i = 0; i < 3; i++)
{
int count = 0;
// Loop through each column checking if char
for (int j = 0; j < 3; j++)
{
if (board[i][j] == player)
{
count++;
}
}
// If we have 3, it means they have the row so they win.
if (count == 3)
{
return true ;
}
}
return false ;
}
Last edited on Feb 19, 2013 at 6:21pm Feb 19, 2013 at 6:21pm UTC
Feb 19, 2013 at 8:55pm Feb 19, 2013 at 8:55pm UTC
On line 55, switch char *line to char line[4] and it will work much better for you. Either way you're doing no bounds checking on the input so this should be fine.
Consider using getline(cin,line) and/or strings if your professor allows them. That way, you can clean the input much easier and don't run into seg faults.
Also, this program doesn't win on input: x.o oox o.x , which should let o win. Something to consider for later. :)
Feb 19, 2013 at 11:56pm Feb 19, 2013 at 11:56pm UTC
Wow thank you! Now i just have to figure out why it wont print the winner haha