试图阻止用户输入字符。这段代码在我的脑海中是有道理的。我做的第一条if语句按预期工作(它可以防止用户输入字符)。但是,当用户做出正确选择时,交换机将直接进入默认情况。在我输入错误处理if语句之前,交换机正常工作。为帮助不确定为什么代码不起作用C++简单
void Input()
{
char errorhandle;
int a;
cout << "It's " << player << "'s turn Enter where you want your shape: ";
cin >> errorhandle;
if (errorhandle < '0' || errorhandle > '9')
{
cout << "You have not entered a number try again!" << endl;
Input();
}
else
{
a = (int)errorhandle;
}
switch (a)
{
case 1:
if (board[0][0] == '1')
{
board[0][0] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 2:
if (board[0][1] == '2')
{
board[0][1] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 3:
if (board[0][2] == '3')
{
board[0][2] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 4:
if (board[1][0] == '4')
{
board[1][0] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 5:
if (board[1][1] == '5')
{
board[1][1] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 6:
if (board[1][2] == '6')
{
board[1][2] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 7:
if (board[2][0] == '7')
{
board[2][0] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 8:
if (board[2][1] == '8')
{
board[2][1] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
case 9:
if (board[2][2] == '9')
{
board[2][2] = player;
}
else
{
cout << "The place is already in use, try again!" << endl;
Input();
};
break;
default:
cout << "You have entered an invalid option, try again" << endl;
Input();
}
}欢呼
错误消息/正在发生的事情的解释将有所帮助。 –
你显然必须重构你的代码以避免重复。另外,从编译器提供错误文本。 –
您可能的意思是!=而不是==每个case语句后立即 – kvr