I made a tic-tac-toe game which works good. Recently I decided to add a reset game feature.
Here is the part where I take input from user
void playerMove() //Gets the player move and updates the box variables
while(1) //Set's loop if the player enters a invalid input
cout << "\n Player " << player << "'s turn!(Press 0 to reset the game!): ";
cin >> boxnumber;
if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0) // Checks if the input is valid or not
system("CLS");//If invalid, show error and loop back to start to get new input
cout << "\n Invalid Input! Try again!\n";
}else if(boxnumber == 0)
box[boxnumber-1] = player;//If inputs are fine, set the box variable's and break out of loop!
if statement, put the range checks in front of the value checks. That is, change
if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0)
if(boxnumber < 0 || box number > 9 || box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O')
That takes advantage of short-circuiting: if the input value is less than 0 or greater than 9 the value checks won't be executed. That will avoid checking things like
box, which isn't valid.
That still leaves a problem: if the user inputs 0, this code will happily check
box[-1], which is also out of range. To get rid of this, move the branch of the
if statement that tests
box number == 0 in front of this part:
if (box number == 0) // whatever else if (box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0) // whatever else