[英]Loop if i input letters or special characters
我不知道發生了什么,但是每次我輸入字母和特殊字符時它都會瘋狂循環,我不知道如何糾正它。 這是我從克勞德的部分認為的。
#include<iostream>
using namespace std;
int main()
{
int a,b;
Claude:
{
cout<<"Please Enter Your Pin: ";
cin>>a;
cout<<endl;
system("cls");
cin.get();
}
if(a==1234)
{ Josh:
cout<<"Choose An Option: "<<endl;
cout<<"1: Withdraw 2: Check Balance";
cout<<endl;
cout<<"3: Deposit 4: Exit";
cout<<endl;
cout<<"Enter Here: ";
cin>>b;
system("cls");
}
else
{
cout<<"Incorrect Pin, Please Try Again"<<endl;
cout<<endl;
cout<<"Press Any Key To Continue "<<endl;
system("pause>nul");
system("cls");
goto Claude;
}
if(b==1)
{
cout<<"How Much: ";
}
else if (b==2)
{
cout<<"2000.00";
}
else if(b==3)
{
cout<<"Nothing To Withdraw";
}
else if(b==4)
{
cout<<"test";
}
else
{
cout<<"Please Enter Valid Input, Press Any Key To Continue ";
cin.get();
system("cls");
goto Josh;
}
return 0;
}
代碼工作正常且沒有錯誤並且工作正常。 請在您自己的開發 C++ 中查找結果。
當你輸入 'a' 時,沒有什么可以吃掉輸入的。 這將繼續失敗,變得“瘋狂”
cin >> a;
將數字讀入 a。 如果無法讀取,則設置錯誤並且不讀取任何內容。
您必須清除控制台輸入緩沖區 (std::cin)。
你可以用 cin.clear() 和 cin.ignore() 做到這一點
//...
cout<<endl;
cout<<"Press Any Key To Continue "<<endl;
cin.clear( );
cin.ignore( 10000, '\n' );
//...
當它發生在你重新進入喬希goto語句和CIN >> B不接受,因為在以前的InputStream值的輸入所以,僅僅通過調用cin.ignore(清除的InputStream);
#include<iostream>
#include<limits>
using namespace std;
int main()
{
int a,b;
Claude:
{
cout<<"Please Enter Your Pin: ";
cin>>a;
cout<<endl;
system("cls");
cin.get();
}
if(a==1234)
{
Josh:
cout<<"Choose An Option: "<<endl;
cout<<"1: Withdraw 2: Check Balance";
cout<<endl;
cout<<"3: Deposit 4: Exit";
cout<<endl;
cout<<"Enter Here: ";
//cin.ignore(numeric_limits<streamsize>::max(),'*');
cin>>b;
system("cls");
}
else
{
cout<<"Incorrect Pin, Please Try Again"<<endl;
cout<<endl;
cout<<"Press Any Key To Continue "<<endl;
system("pause>nul");
system("cls");
goto Claude;
}
if(b==1)
{
cout<<"How Much: ";
}
else if (b==2)
{
cout<<"2000.00";
}
else if(b==3)
{
cout<<"Nothing To Withdraw";
}
else if(b==4)
{
cout<<"test";
}
else
{
cout<<"Please Enter Valid Input, Press Any Key To Continue ";
cin.clear();
cin.ignore();
cin.get();
cin.get();
system("cls");
goto Josh;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.