CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 17

Threaded View

  1. #1
    Join Date
    Nov 2009
    Location
    UK
    Posts
    166

    Ned to optimize the code

    simple xox game but i kinda got a problem, that if statement works but it's too long, any ideas how to change into something better? and is there any better way to say the user won without having that "break;"?

    thanks for any help =)

    Code:
    #include <iostream>
    #include <string>
    
    void main()
    {
    char grid[3][3] = {'.','.','.','.','.','.','.','.','.'};
    int row = 0;
    int col = 0;
    char input;
    std::string msg = "";
    
    
    std::cout<< "  0 1 2"<<"\n"<<"0 . . ."<<"\n"<<"1 . . ."<<"\n"<<"2 . . ."<<std::endl; 
    
    for(int k=0;k<9;k++)
    {
    	std::cout<< "Enter row: ";
    	std::cin>> row;
    	std::cout<< "Enter collum: ";
    	std::cin>> col;
    	std::cout<< "Enter X or O: ";
    	std::cin>> input;
    	grid[row][col]= input;
    
    for(int i=0;i<3;i++)
    {
    	for(int j=0;j<3;j++)
    	{
    		std::cout<< grid[i][j];
    	}
    	std::cout<< "\n";
    }
    if(((((((((grid[0][0]=='x')&&(grid[0][1]=='x')&&(grid[0][2]=='x')||
    (grid[1][0]=='x')&&(grid[1][1] == 'x')&&(grid[1][2]=='x')||(grid[2][0]=='x')&&
    (grid[2][1]=='x')&&(grid[1][2]=='x')))))))))
    {
    	msg = "you won";
    	break;
    }
    else
    {
    	msg = "You lost";
    }
    }
    std::cout<< msg;
    }
    the output
    Last edited by Mariusmssj; November 30th, 2009 at 01:34 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured