why the player is not switching between "X" and "O"?

I cannot understand why the player is not switching between "X" and "O"?

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
  #include<stdio.h>
#include<iostream>
using namespace std;

char matrix[3][3] = { '.','.','.','.','.','.','.','.','.' };
char player = 'X';

void display()
{
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)

		{
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}
}

void togglePlayer(char player)
{
	if (player=='O')
	{
		player = 'X';
	}
	else player = 'X';
}

void input()
{
	int num;
	cout << "Enter the desired matrix" << endl;
	cin >> num;
	if (num == 1)
	{
		matrix[0][0] = player;
	}
	else if (num == 2)
	{
		matrix[0][1] = player;
	}
	else if (num == 3)
	{
		matrix[0][2] = player;
	}
	else if (num == 4)
	{
		matrix[1][0] = player;
	}
	else if (num == 5)
	{
		matrix[1][1] = player;
	}
	else if (num == 6)
	{
		matrix[1][2] = player;
	}
	else if (num == 7)
	{
		matrix[2][0] = player;
	}
	else if (num == 8)
	{
		matrix[2][1] = player;
	}
	else if (num == 9)
	{
		matrix[2][2] = player;
	}

}

int main()
{
	while (true)
	{
		display();
		togglePlayer(player);
		input();
	}
	system("pause");
	return 0;
}
closed account (E0p9LyTq)
why the player is not switching between "X" and "O"?

Look closely at your togglePlayer() function. You are setting player to 'X' no matter what.

Try:
1
2
3
4
5
6
7
8
void togglePlayer(char player)
{
	if (player=='O')
	{
		player = 'X';
	}
	else player = 'O';
}
Don't forget to pass `player' by reference
1
2
3
4
void togglePlayer(char &player) 
{
  // ...
}
Last edited on
@FurryGuy Even though I tried your function, it is still the same (not switching between "X" and "O")
@philip1999,
Please read @mbozzi's post. You need that ampersand & in the parameter list of the function definition. Otherwise player will be passed by value: i.e. only a copy goes to your function and nothing goes back. I appreciate that this may be different from some other programming languages.
Last edited on
Topic archived. No new replies allowed.