C++井字棋游戏X字符无法显示问题技术求助
Hey there! Let's dig into why your X isn't showing up in your C++ Tic-Tac-Toe game—this is a classic character-to-integer conversion gotcha, so let's break it down step by step.
1. 字符转数字的致命错误
The biggest issue is in your playgame() function, right here:
int entered_num = entered - 0;
When you type a number like '1', it's stored as an ASCII character (value 49). To convert it to the integer 1, you need to subtract the ASCII value of '0' (which is 48), not the integer 0. Subtracting 0 leaves you with the raw ASCII value (49 for '1'), which makes index = 49 - 1 = 48—way outside your 3x3 grid's index range (0-2). That means your X is being written to an invalid memory location, so it never shows up on the board.
Fix it by changing that line to:
int entered_num = entered - '0';
2. 棋盘初始化的潜在问题
Your generateGrid() function uses std::to_string(number).c_str()[0] to create the numbered grid, which has a hidden bug: std::to_string() returns a temporary string that gets destroyed immediately after the line runs. The c_str() pointer points to memory that's no longer valid, so your grid might end up with garbage characters.
A safer, simpler way to generate the number characters is using ASCII offsets:
void generateGrid() { int number = 1; for (int x = 0; x < GRID_SIZE; x++) { for (int y = 0; y < GRID_SIZE; y++) { map[x][y] = '0' + number; // Directly compute the number character number += 1; } } }
3. 小优化建议
- You don't need the
(char)cast when assigning'X'—'X'is already achartype. - Make sure
GRID_SIZEis defined as a constant (likeconst int GRID_SIZE = 3;) to avoid mismatches across functions. - If you ever add other input methods (like
cin >>), remember to clear the newline from the input buffer before usinggetline(), otherwise it might read an empty string.
修正后的关键代码片段
void playgame() { std::string input; while (true) { std::cout << "Go player one" << std::endl; getline(std::cin, input); if (!input.empty()) { // Better check than comparing to " " char entered = input[0]; // No need for c_str() here if (entered >= '1' && entered <= '9') { int entered_num = entered - '0'; // Fixed conversion int index = entered_num - 1; int row = index / 3; int col = index % 3; char grid_position = map[row][col]; if (grid_position == 'X' || grid_position == 'O') { std::cout << "Space taken. Try again" << std::endl; } else { map[row][col] = 'X'; // Removed unnecessary cast break; } } else { std::cout << "Only numbers 1 - 9 are allowed" << std::endl; } } else { std::cout << "You have to enter something, try again" << std::endl; } } } void generateGrid() { int number = 1; for (int x = 0; x < GRID_SIZE; x++) { for (int y = 0; y < GRID_SIZE; y++) { map[x][y] = '0' + number; // Fixed grid initialization number += 1; } } }
After making these changes, your X should show up exactly where you expect it on the board. Let me know if you run into any other kinks!
内容的提问来源于stack exchange,提问作者winston mcnair

