Question

I am trying to check and see if my 2d array tic tac toe board only contains x's and o's, however I am not sure how to do this. This is the code given to me...

#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);
   }
Was it helpful?

Solution

Just do a loop over the array and check each:

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;

But better do your data validation early, e.g. on input directly.

OTHER TIPS

You could iterate over the whole board, like so:

for(int r = 0; r < SIZE; r++){
    for(int c = 0; c < SIZE; c++){
        // some validation code
    }
}

But a better solution would probably be to validate the characters as they're entered:

for(int r = 0; r < SIZE; r++){
    for(int c = 0; c < SIZE; c++){
        char in = 'a';
        while(in != 'x' || in != 'o'){
            cin >> in;
        }
    }
}

Along with whatever useful feedback you want to give the user

#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' ); } );
    } );

For example

#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;
}

I am using default capture [=] because as far as I know MS VC++ has a bug.

You can read about it here Though it is written in Russian you can translate it to English using an online tool,for example google translate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top