我正在检查并查看我的2d阵列tic tac toe board是否仅包含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;
// TBA
if (!valid)
{
cout << "Sorry, you can only enter x's and o's\n";
exit(1);
}
答案 0 :(得分:1)
只需在数组上循环并检查每个:
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
if(board[i][j] != 'x' and board[i][j] != 'o')
valid = false;
但最好尽早进行数据验证,例如直接输入。
答案 1 :(得分:0)
你可以迭代整个董事会,如下:
for(int r = 0; r < SIZE; r++){
for(int c = 0; c < SIZE; c++){
// some validation code
}
}
但更好的解决方案可能是在输入字符时对其进行验证:
for(int r = 0; r < SIZE; r++){
for(int c = 0; c < SIZE; c++){
char in = 'a';
while(in != 'x' || in != 'o'){
cin >> in;
}
}
}
除了您想要给用户的任何有用的反馈
答案 2 :(得分:0)
#include <algorithm>
#include <iterator>
//,,,
bool valid = std::all_of( std::begin( board ), std::end( board ),
[=]( const char ( &row )[SIZE] )
{
return std::all_of( std::begin( row ), std::end( row ),
[]( char c ) { return ( c == 'x' || c == 'o' ); } );
} );
例如
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
int main()
{
const int SIZE = 3;
char board[SIZE][SIZE] = { { 'x', 'x', 'o' }, { 'o', 'x', 'o' }, { 'o', 'x', 'x' } };
bool valid = std::all_of( std::begin( board ), std::end( board ),
[=]( const char ( &row )[SIZE] )
{
return std::all_of( std::begin( row ), std::end( row ),
[]( char c ) { return ( c == 'x' || c == 'o' ); } );
} );
std::cout << std::boolalpha << is_valid << std::endl;
}
我正在使用默认捕获[=]因为据我所知MS VC ++有一个错误。
你可以阅读here 虽然它是用俄语写的,但您可以使用在线工具将其翻译成英语,例如谷歌翻译。