I'm trying to code a tic tac toe game. I'm adding some check functions and I've a problem with the if statement in the checkvalidmove(int move);. It doesn't return the exact value but just false when condition is true or vice-versa... is like it skip control ad go ahead... I tried to solve in some ways, I change the
function's parameters, I use variable or not to return the value, I tried to
use else statement or not and so on. I spent some hours on it but I don't know
why it give me that problem, so here there's the code.
@Thomas1965 I use two nested loops to search through matrix and compare each element with variable move that I convert into a char. Anyway thanks for your answer, I'll try that method :)
Playing with the program a bit and working off of ne555's suggestion I came up with this in "main":
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
cin >> mossa;
validmove = checkvalidmove(mossa);
//cout << '\n' << boolalpha << validmove << '\n' << endl;
if (!validmove)
{ // <--- if "validmove" is false.
std::cout << "\n That space is taken. Please try again.\n" << std::endl;
}
else
move(mossa, turno); // <--- If "validmove" is true.
if (validmove)
{
I left the "cout" statement in to show you the use of "boolalpha" which prints "false" or "true" instead of "0" or "1". Not that this line has any real use that I can see unless for testing.
Then in the function "checkvalidmove" I made this change: char convertmove = static_cast<char>(move + '0');. Changing from a "char" to an "int" is easier, but it is not as easy going from an "int" to a "char hence the "static_cast".
Instead of trying to remember the decimal value of zero just use the character zero. Thes is even better when you are working with upper and lower case letters. This way you do not have to hunt for the decimal value.
Thanks a lot for your answers, they helped me to figure out the problem and introduced me to the static_cast. I don't really know why I made that mistake maybe too hours of programming :).
Sometimes it is the simple things that are hard to find after of working on the program.
I find there are times that just walking away from the problem for a few minutes and not thinking about it can help greatly. Other times just giving up for the day and getting some sleep helps.
When you look back yo will realize that a good programmer just does not want to give up. in that case see previous paragraph. Or print it out and put it up in frount of you, so you can read it often.