So I'm in the process of troubleshooting a few issues in my code, and this seems to have me stumped.
A quick run down:
Trying to code a console based tic tac toe game (I'm very newbie).
I have a function that checks for a valid move.
If the move is valid it returns a 0
if the move is not valid it returns a 1
//win is a function that checks the board for a win/draw/continue senario
while (win != 1 && win != 2) {
cout << "It's " << player << "'s Turn. Move: ";
cin >> turn;
//initializing valid to the value of 0 if checkvalid is appropriate and 1 if //checkvalid is not.
valid = checkvalid(turn);
//the issue?
while (valid == 1) {
cout << "Invalid move. Move: ";
cin >> turn;
valid = checkvalid(turn);
}
if (valid == 0) {
//continues game
Now i understand that there are a few different ways i could have done this (boolean rather than an int return, a do-while loop, etc), But I've tried a few of those and was just curious if someone can enlighten me a bit as to why this is not working.
Okay, before I look at all of your code I have to say that your function could be cleaned up quite a bit.
Why not if (turn >= 1 && turn <= 9)
...
or even better: return (turn >= 1 && turn <= 9);
Edit: Also, try to figure out how to get rid of that valid variable. You really don't need it.
Does your game allow you to enter another move? Or does it just fill the screen with the message "Invalid move. Move: " and not let you enter another number?
//new function code now also checks that the move hasn't already been made
int checkvalid(int turn, char board[]) {
if (turn >= 1 && turn <= 9 && board[turn - 1] != 'X' && board[turn - 1] != 'O') {
return 0;
}
else {
return 1;
}
}
// new loop/check code minus the valid variable
while (win != 1 && win != 2) {
cout << "It's " << player << "'s Turn. Move: ";
cin >> turn;
checkvalid(turn, board);
while (checkvalid(turn, board) != 0) {
cout << "Invalid move. Move: ";
cin >> turn;
checkvalid(turn, board);
}
if (checkvalid(turn, board) == 0) {
@BrBrowni3141
Is this kind of what you meant? I apologize for my terrible code style, i'm still in the process of learning to think in code. I went ahead and got rid of valid but it still seems to just spit out
cout << "Invalid move. Move: ";
over and over again. It's not prompting for input from the cin statement as i'd suspect. :(
@Computergeek01
It seems to just loop over and over and allow no input.
While the loop actually does work when entering a valid integer as input, it freaks out when you enter any sort of non-number ASCII character. I'd guess this is do to my answer variable being of type int and not char. for instance: