Use an array for s:
char s[9] = {'-', '-', '-', '-', '-', '-', '-', '-', '-'};
Keep in mind that arrays are accessed starting at 0, not 1, so s goes from s[0] to s[8] rather than s[1] to s[9].
Now lines 28-37 become:
1 2 3
|
cin>>human;
--human; // convert from human friendly 1-9 to computer friendly 0-8
if s[human]=='_'){s[human]='X';}
|
Lines 51-59 can get similar treatment.
There's a problem here (and in your orignal code). What if the user enters an invalid number? Let's worry about that later.
You could create a function to tell if someone has won:
1 2 3 4 5 6 7 8 9 10 11 12
|
bool isWinner(char mark)
{
if(s[0]==mark&&s[1]==mark&&s[2]==mark){return true;}
if(s[3]==mark&&s[4]==mark&&s[5]==mark){return true;}
if(s[6]==mark&&s[7]==mark&&s[8]==mark){return true;}
if(s[0]==mark&&s[3]==mark&&s[6]==mark){return true;}
if(s[1]==mark&&s[4]==mark&&s[7]==mark){return true;}
if(s[2]==mark&&s[5]==mark&&s[8]==mark){return true;}
if(s[0]==mark&&s[4]==mark&&s[8]==mark){return true;}
if(s[6]==mark&&s[4]==mark&&s[2]==mark){return true;}
return false;
}
|
Now lines 38-45 and 84-91 become
if (isWinner('X')) {cout << "X wins";break;}
and lines 60-67 and 106-113 become:
if (isWinner('O')) {cout << "O wins";break;}
In general, any time you find yourself writing the same or very similar code more than once, try to figure a way to turn it into a function. Also, anytime you find yourself writing variables with names like x1, x2, x3, consider making an array (or vector) instead.