Checking for tic-tac-toe winner

Here is the function..
1
2
3
4
5
6
7
8
9
10
11
12
int CheckForWinner( char spaces[9] )
{
	//Check Rows
	for( int i = 0; i < 3; i+=3 )
	{
			if( spaces[i] == spaces[i+1] == spaces[i+2] == 'X' )
				return 1;
			else if( spaces[i] == spaces[i+1] == spaces[i+2] == 'O' )
				return 2;
	}
        return 0;
}


And this is also relevant...
1
2
3
4
5
6
7
8
9
10
11
12
	// Check and react in case of a winner
		switch( CheckForWinner( spaces ) )
		{
		case 1:
			cout << endl << endl << "Player 1 has won!!!";
			break;
		case 2:
			cout << endl << endl << "Player 2 has won!!!";
			break;
		default:
			break;
		}


That should check to see if anyone has won across all rows, but it doesnt seem like the function is working. What could be the problem?
I can't log onto this site without seeing 2 or 3 tic-tac-toe questions this week. There must be an assignment due or something for a course that references this site a lot.


http://cplusplus.com/forum/beginner/58046/
I think its just because it is a simple game and beginners like myself want to practice. So do you see what could be wrong with my function?
if( spaces[i] == spaces[i+1] == spaces[i+2] == 'X')

doesn't work in C++

if( spaces[i] == 'X' && spaces[i+1] == 'X' && spaces[i+2] == 'X')

is what you need.

The first version is evaluated left to right, so -- assuming all are 'X' (ascii 88) -- it ends up as (evaluating the leftmost two terms each time)

if( spaces[i] == spaces[i+1] == spaces[i+2] == 'X') // 'X' == 'X' -> true (88 == 88)

if( true == spaces[i+2] == 'X') // true == 'X' -> false (1 != 88)

if( false == 'X') // false == 'X' -> false (0 != 88)

if( false ) // :-(
Last edited on
Thank you!
Topic archived. No new replies allowed.