检查二维井字阵列位置c++

Checking 2d tic tac toe array locations c++

本文关键字:阵列 位置 c++ 二维 检查      更新时间:2023-10-16

我正在尝试检查我的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++有一个错误。

你可以在这里阅读虽然它是用俄语写的,但你可以使用在线工具将其翻译成英语,例如谷歌翻译。