無法弄清楚如何防止此函式中的遞回,有什么建議或建議嗎?我已經嘗試了幾個我自己的解決方案,但是如果輸入錯誤并重復輸入,就會遇到程式崩潰的錯誤。提前致謝,DK。
static void CheckPlayerInput()
{
// gets the character entered (as a char)
cin >> input;
//check is actually a char
if (cin.fail())
{
//more recursion, could cause issues, could you find another way?
cout << "Invalid character, try again!" << endl;
CheckPlayerInput();
}
//converts char to upper case
input = toupper(input);
//check the input character
// maps the input keys to the grid reference
//calling the FillSquare method
switch (input)
{
case '1': FillSquare(0, 0); break; //top-left
case '2': FillSquare(0, 1); break; //top-centre
case '3': FillSquare(0, 2); break; //top-right
case '4': FillSquare(1, 0); break; //middle-left
case '5': FillSquare(1, 1); break; //middle-centre
case '6': FillSquare(1, 2); break; //middle-right
case '7': FillSquare(2, 0); break; //bottom-left
case '8': FillSquare(2, 1); break; //bottom-centre
case '9': FillSquare(2, 2); break; //bottom-right
//IF NOT ANY OF THE ABOVE
default:
{
//more recursion, could cause issues
//
cout << "Invalid character, try again!" << endl;
CheckPlayerInput();
}
break;
}
}
uj5u.com熱心網友回復:
改用do while回圈
static void CheckPlayerInput()
{
bool invalid = false;
do
{
invalid = false;
// gets the character entered (as a char)
cin >> input;
...
default:
{
//more recursion, could cause issues
//
cout << "Invalid character, try again!" << endl;
invalid = true;
}
break;
}
}
while(invalid);
}
只要輸入無效,while回圈就會重復
uj5u.com熱心網友回復:
我想有很多不同的方法來實作它。以下可能是我的方法。
筆記:
- 填充正方形感覺像是一項專門的任務,因此應該在它自己的功能內。
- 也許您應該使用非靜態/非全域方法,而是使用物件。
- 您的方法
CheckPlayerInput不檢查輸入。相反,它正在處理它。
static bool
_fillSquare(char type)
{
switch (type)
{
case '1': FillSquare(0, 0); break; //top-left
case '2': FillSquare(0, 1); break; //top-centre
case '3': FillSquare(0, 2); break; //top-right
case '4': FillSquare(1, 0); break; //middle-left
case '5': FillSquare(1, 1); break; //middle-centre
case '6': FillSquare(1, 2); break; //middle-right
case '7': FillSquare(2, 0); break; //bottom-left
case '8': FillSquare(2, 1); break; //bottom-centre
case '9': FillSquare(2, 2); break; //bottom-right
default : return false;
}
return true;
}
// this method does not `check` the player input, but it
// `processes` it. The name should reflect that.
static void
processPlayerInput()
{
// try to retrieve and process input until
// a valid input was given
while (true)
{
cin >> input;
if (!cin.fail ())
continue;
input = toupper(input);
bool success = _fillSquare(input);
if (!success)
{
cout << "Invalid character, try again!" << endl;
continue;
}
return;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328833.html
