Thread: check characterin 2D array

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    11

    Angry check characterin 2D array

    Hi
    how can I check for certain character in rows or columns of 2-D array ?
    for example , if array is :
    Code:
    int main()
    {
        int i,j;
    	
    	char board[3][3]={{'X','X','O'},
    					  {' ','X','O'},
    					  {' ','O','O'}};
    	for(i=0; i<3; i++)
    	{
    		for(j=0; j<3; j++)
    			cout<<board[i][j]<<"\t";
    	cout<<endl;
    	}
    }
    how can I check that if X is used in whole row, return 1.

    Thanks

  2. #2
    Registered User
    Join Date
    Nov 2010
    Posts
    11
    Code:
    if(board[1] == "XXX") return 1;

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    C++ Simple Tic Tac Toe - C And C++ | Dream.In.Code

    Don't post again until you've read and understood this
    How To Ask Questions The Smart Way
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463
    Quote Originally Posted by eros View Post
    Code:
    if(board[1] == "XXX") return 1;
    don't think that will work since "XXX" is a string literal.

    how can I check for certain character in rows or columns of 2-D array ?
    you have to iterate over each row of the 2d array to check.

    Code:
    int win; 
    for ( int i = 0 ; i < 3 ; ++i)
    {
       for( int j = 0 ; j < 3; ++ j)
            {
                if( board[i] == 'somechar')
                   win++;
             }
      if ( win = 3) return 1; 
    }
    "All that we see or seem
    Is but a dream within a dream." - Poe

  5. #5
    Registered User
    Join Date
    Jan 2011
    Posts
    87
    here is one way to test for diagonals
    Code:
    if(board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X')
         return 1;
    but i think there is a better way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  3. 2D array becoming "deallocaded"
    By Aaron M in forum C Programming
    Replies: 2
    Last Post: 09-23-2006, 07:53 AM
  4. Copying from one 2d array to another....with a twist
    By Zildjian in forum C++ Programming
    Replies: 2
    Last Post: 10-24-2004, 07:39 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM