I make tictactoe 2d array but my code run like this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I make tictactoe 2d array but my code run like this

1 || 2 || 3 4 || 5 || 6 7 || 8 || 9 Enter: 1 || || 4 || 5 || 6 7 || 8 || 9 There is my code: #include <iostream> #include <string> #include <stdio.h> using std::cout; void show(char pos[3][3]){ //system("cls"); int n = 1; for (int i=0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout<<pos[i][j]; if(j < 2){ printf(" || "); } } printf("\n"); } } int main() { char pos[3][3], e; int n = 1; char player = 'O'; bool End = false; for (int i=0; i < 3; i++) { for (int j = 0; j < 3; j++) { pos[i][j] = '0' + n; n++; } } do { show(pos); scanf("%d", &e); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if(pos[i][j] == e){ pos[i][j] = player; if (player == 'X') player = 'O'; else player = 'X'; } While(true); } }

18th Jul 2021, 3:11 PM
Global Long
Global Long - avatar
2 Answers
+ 1
I like your code. It is very clean and readable. I think the problem is the format specifier in scanf(). It is storing an integer in a location that is allocated for only char variable and overwriting the first three elements of the pos[][] array with null, null, ctrl-a. Change the format specifier to %c. Edit: Later I noticed that this is in C++ but using C's scanf(). It would be better to replace scanf() with std::cin >> e;
18th Jul 2021, 5:54 PM
Brian
Brian - avatar
+ 1
Its work thanks Mr. Brian
19th Jul 2021, 2:46 AM
Global Long
Global Long - avatar