#include <iostream>enum Cell {Empty=' ', X='X', O='O'};typedef Cell Board[9];void drawLine(Cell a, Cell b, Cell c) { std::cout << " | | | |\n" << " | "<<static_cast<char>(a) << " | " <<static_cast<char>(b) << " | " <<static_cast<char>(c) << " |\n" << " |_____|_____|_____|" << std::endl; }void draw(const Board &board) { std::cout << " _________________ " << std::endl; for(int c = 0; c < 3; ++c) drawLine(board[c*3+0],board[c*3+1],board[c*3+2]); }Cell testDirection(const Board &board, int cell, int offset) { Cell first(board[cell]); for(int c = 1; c<3; ++c) if(board[cell+offset*c] != first) return Empty; return first; }Cell findWinner(const Board &board) { Cell result; for(int cell = 0; cell < 3; ++cell) { if(Empty != (result = testDirection(board, cell, 3))) return result; if(Empty != (result = testDirection(board, cell*3, 1))) return result; } if(Empty != (result = testDirection(board, 0, 4))) return result; if(Empty != (result = testDirection(board, 2, 2))) return result; return Empty; }bool boardFilled(const Board &board) { for(int cell = 0; cell < 9; ++cell) if(board[cell] == Empty) return false; return true; }void clearBoard(Board &board) { for(int cell = 0; cell < 9; ++cell) board[cell] = Empty; }bool setBoard(Board &board, Cell player, char position) { if(position < '1' || position > position > '9') return false; // Not a valid position int index = position-'1'+6; if(position > '6') index = position-'7'; else if(position > '3') index = position-'4'+3; if(board[index] != Empty) return false; // Already something there. board[index] = player; return true; }int main() { Board board; Cell player = X; clearBoard(board); while(true) { draw(board); do { std::cout << static_cast<char>(player) << ", enter your move (1-9): "; std::cout.flush(); std::cin.sync(); } while(!setBoard(board, player, std::cin.get())); Cell winner(findWinner(board)); if(Empty != winner) { std::cout << static_cast<char>(winner) << " wins!" << std::endl; clearBoard(board); } else if(boardFilled(board)) { std::cout << "Draw!" << std::endl; clearBoard(board); } if(player == X) player = O; else player = X; } // Never reached. . . return 0; }
Edit: I hate tab characters.