I'm still quite new to c++ and just experimenting with the language.
I have recently created a 'tictactoe' game.
I have created this simple looking function to get the users board position (from 1 to 9). It seems to work fine but I found a weird bug so to call it;
Whenever I enter a 12 digit number or higher the loop just carries on forever printing 'Invalid position!' and on to the next line 'Choose your position 1-9: '.
I am using visual studio to write code. Is it something with the code or is it perfectly fine? I'm eager to find out to learn from it.
Here's the function:
int getUserPosition()
{
int position;
while (true)
{
cout << " Choose your position 1-9: " << endl;
cin >> position;
if (position < 1 or position > 9)
{
cout << "Invalid position!" << endl;
}
else if (board[position - 1] == 'X')
{
cout << "This position has been taken!" << endl;
}
else
{
return position;
break;
}
}
}
cin >> position;You have no idea whether or not you read good data. If you read bad data, you want to discard the bad data andclearthe error flags before continuing. Something likeif (cin >> position) { do stuff with position } else { clean up bad input }>>for user input. It has the same problems asscanf. Also, code afterreturnis unreachable.