提问人:Adrian Pena 提问时间:10/25/2023 最后编辑:kiner_shahAdrian Pena 更新时间:10/25/2023 访问量:42
验证 2D 字符数组的输入
Validating inputs for a 2D- Character Array
问:
我有一些代码正在处理,但我被卡住了。如何检查 2D 字符数组的字符输入是否正确?我正在模拟井字游戏,并且只需要“x”和“o”作为我的输入,其他任何内容都应该产生”cout << "Sorry you can only enter 'x' and 'o'" << endl; exit(1);
"
这是我到目前为止尝试过的,但这不起作用!有人可以向我解释一下吗?我是 c++ 的初学者,所以我只知道基础知识,但基本上我必须检查所有 9 个数组位置是否有正确的输入或 .'x'
'o'
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
// Declare 2D array
const int SIZE = 3;
char board[SIZE][SIZE];
// Read x's and o's
cout << "Enter x's and o's on board (L-R, T-B): ";
for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++)
cin >> board[r][c];
// Print 2D array
cout << "\n+---+---+---+\n";
for (int r = 0; r < SIZE; r++) {
cout << "| ";
for (int c = 0; c < SIZE; c++)
cout << board[r][c] << " | ";
cout << "\n+---+---+---+\n";
}
// Check board contains only x's and o's
bool valid = true;
if (board[SIZE][SIZE] != 'x' || board[SIZE][SIZE] != 'o')
valid = false;
if (!valid) {
cout << "Sorry, you can only enter x's and o's\n";
exit(1);
}
// Check first diagonal to see who wins
char winner = ' ';
if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]))
winner = board[0][0];
// Check second diagonal to see who wins
if ((board[2][0] == board[1][1]) && (board[1][1] == board[0][2]))
winner = board[0][0];
// Check rows to see who wins
for (int r = 0; r < SIZE; r++)
if ((board[r][0] == board[r][1]) && (board[r][1] == board[r][2]))
winner = board[r][0];
// Check columns to see who wins
for (int c = 0; c < SIZE; c++)
if ((board[0][c] == board[1][c]) && (board[1][c] == board[2][c]))
winner = board[c][0];
// Print winner
if (winner != ' ')
cout << "Congratulations " << winner << " is the winner\n";
else
cout << "Sorry, no one wins\n";
return 0;
}
答: 暂无答案
评论
board[SIZE][SIZE] != 'x' || board[SIZE][SIZE] != 'o'
始终是正确的。如果字符等于 ,则它显然不等于 ,反之亦然。你的意思是代替x
o
&&
||
board[SIZE][SIZE]
0
SIZE-1
bool isValidEntry(char c) { return c == 'x' || c == 'o'; }
main
if (!isValidEntry(board[r][c]))