检查二维井字阵列位置c++
Checking 2d tic tac toe array locations c++
我正在尝试检查我的2d数组井字板是否只包含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'sn";
exit(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;
但最好尽早进行数据验证,例如直接输入。
您可以在整个板上进行迭代,如下所示:
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;
}
}
}
连同您想要给用户的任何有用的反馈
#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++有一个错误。
你可以在这里阅读虽然它是用俄语写的,但你可以使用在线工具将其翻译成英语,例如谷歌翻译。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- OpenMP阵列性能较差
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 访问特定阵列位置/索引时出现分段错误
- 访问字符阵列中不可用的内存位置(超出范围值)
- 如何将X重置回阵列中的原始位置
- mpi_bcast,将阵列缓冲区广播到接收缓冲区中的特定位置
- C 2D char阵列有时会在随机位置复制数据
- MPI-如何将杂志发送到阵列中的特定位置
- 查找阵列的位置-C
- 阵列相邻位置交换程序需要提示
- 检查阵列位置在C++中是否为空的 CPU 高效方法
- C++阵列在内存中的存储位置
- 从随机起始位置开始的螺旋阵列
- 检查阵列位置是否为空/空
- 检查阵列位置
- 阵列内存位置
- 检查二维井字阵列位置c++