[英]Unsure why code doesn't work C++ simple
試圖阻止用戶輸入字符。 這段代碼在我的腦海中很有意義。 我所做的第一個 if 語句按預期工作(它阻止用戶輸入字符)。 但是當用戶做出正確選擇時,開關直接進入默認情況。 在我輸入錯誤處理 if 語句之前,開關工作正常。 為幫助歡呼
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();
}
}
問題是,當您確定錯誤時,您再次調用您的函數:
Input();
當用戶然后輸入一個好的數字時,它會使用好的輸入執行切換。 然后它返回給調用者,在錯誤處理后恢復,並使用未初始化a
a 第二次執行 switch
還有另一個問題:當您使用a = (int)errorhandle;
將輸入轉換為整數時a = (int)errorhandle;
, '1' 的輸入將被轉換為 '1' 的 ascii 值而不是 1。所以你的 case 值應該堅持引用的值。
潛在修正:
while ( (cin >> errorhandle) && (errorhandle < '0' || errorhandle > '9') )
cout << "You have not entered a number try again! " << endl;
a = errorhandle-'0';
switch (a)
...
在這一行:
a = (int)errorhandle;
您正在將 ascii char
轉換為int
。 '1' 的值和 1 不一樣。看ascii 表。
同樣在您遞歸調用Input()
您將繼續在未初始化的switch
語句中使用a
。
if (errorhandle < '0' || errorhandle > '9') {
cout << "You have not entered a number try again!" << endl;
Input();
return; // Stop execution after this line.
// This should be done in all cases of a call to input.
} else {
a = (int)(errorhandle - '0');
}
以前的答案解釋了發生了什么,您可以像這樣修復它:
if (errorhandle < '0' || errorhandle > '9')
{
cout << "You have not entered a number try again!" << endl;
Input();
return; // < new | stops the function
}
在這種情況下我會避免遞歸,但這也有效。
並且您不能像那樣將 char 轉換為 int。 甚至不要轉換為 int 只是比較 switch 語句中的 char 值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.