我為我的最終專案創建了一個代碼。在開始時,會詢問用戶使用什么計算器,它是普通計算器還是簡單計算器。但是如果用戶不小心輸入了一個非整數,它會導致無限錯誤回圈,但如果它是一個不在選擇中的整數,它會起作用,因為我創建了一個 while 回圈。我需要幫助我需要做些什么來防止無限回圈。
cout << 1. average calculator: << endl;
cout << 2. simple calculator: << endl;
cout << Enter the Number << endl;
cin >> choice;
while (choice > 2 || choice <= 1)
{
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
cin >> choice;
}
uj5u.com熱心網友回復:
您需要清除輸入緩沖區。此 if 陳述句中的條件也不正確
while (choice > 2 || choice <= 1)
看來你的意思
while (choice > 2 || choice < 1)
while 回圈可以通過以下方式重寫為 do-while 回圈
#include <limits>
//...
bool input_error = false;
do
{
input_error = false;
if ( not ( std::cin >> choice ) )
{
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
input_error = true;
}
else if ( choice < 1 || choice > 2 )
{
input_error = true;
}
if ( input_error )
{
std::cout << "Error! Please choose a number between 1 and 2 only.\n";
std::cout << "Enter the number again: ";
}
} while ( input_error );
uj5u.com熱心網友回復:
而不是使用while回圈,您可以使用switch這樣的
switch(choice //this is the input)
{
case 1:
//the stuff you want to do
break; //always a break
case 2:
//more stuff
break;
default:
//throwing a error
std::cout << "Error, please pick a number between 1 and 2\n";
}
如果你想重復直到你選擇正確的數字,你可以像這樣把switch里面的do while回圈
do
{
switch(choice)
{
//the stuff
}
}while(choice > 2 || choice < 1);
讓我們希望這將有一個美好的一天。
uj5u.com熱心網友回復:
cout << "1. average calculator:" << endl;
cout << "2. simple calculator:" << endl;
cout << "Enter the Number" << endl;
string stringInput;
getline(cin, stringInput);
int choice = atoi(stringInput.c_str());
while(choice < 1 || choice > 2) {
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
getline(cin, stringInput);
choice = atoi(stringInput.c_str());
}
您應該閱讀整行,將其存盤在字串中,然后將該字串轉換為integerusing atoi(). atoi()期望c-string通過,因此std::string應轉換為c-string. 它由stringInput.c_str().
我將 while 條件更改(choice > 2 || choice <= 1)為,(choice < 1 || choice > 2)因為它說要輸入 1 到 2 之間的數字,但是在您輸入數字 1 的條件下會列印"Error! Please choose a number between 1 and 2 only.".
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476193.html
