//*********************cin测试*********************
//non-numeric input skipped
//#include<iostream>
//using namespace std;
//int main()
//{
// int n=0;
// cout<<"Please input a number:"<<endl;
// while(!(cin>>n))
// {
// cin.sync(); //清除缓冲区
// cin.clear(); //清除错误状态
// while(cin.get()!='\n')
// continue;
// cout<<"the input is not a number,please input a number again:"<<endl;
//
// }
// cout<<"the input number n is:"<<n<<endl;
//}
//*******************cin测试1******************************
non-numeric input skipped and char input next
//#include<iostream>
//using namespace std;
//int main()
//{
// int n=0;
// cout<<"Please input a number:"<<endl;
// while(!(cin>>n))
// {
// cin.sync(); //清除缓冲区
// cin.clear(); //清除错误状态
// while(cin.get()!='\n')
// continue;
// cout<<"the input is not a number,please input a number again:";
//
// }
// char ch;
// cin>>ch;
// cout<<"the input number n is:"<<n<<endl;
// cout<<"ch:"<<ch<<endl;
//
// return 0;
//}
//**********************cin test2*************************
//non-numeric input skipped and char input next
#include<iostream>
using namespace std;
int main()
{
int n=0;
cout<<"Please input a number:"<<endl;
// while((!(cin>>n))&&(n!=1)&&(n!=2)) //&&(n!=1)&&(n!=2) invalid
while(!(cin>>n))
{
cin.sync(); //reset input buffer
cin.clear(); //reset error state
while(cin.get()!='\n')
continue; //get rid of bad input
cout<<"the input is not a number,please input again:";
}
// if((n!=1)||(n!=2)) //valid,but only once
// {
// cout<<"Your input is a number,but not 1/2,please input again:";
// cin>>n;
// }
// while((n!=1)||(n!=2)) //not valid
// {
// cin.sync(); //reset input buffer
// cin.clear(); //reset error state
// while(cin.get()!='\n')
// continue; //get rid of bad input
// cout<<"the input is not a number,please input again:";
//
// }
if(n==1) cout<<"n:"<<n<<endl;
else if(n==2) cout<<"n:"<<n<<endl;
else {
cout<<"Your input is a number,but not 1/2,please input again:";
(cin>>n).get(); //valid,but only once
}
char ch;
cout<<"please input a char:";
cin>>ch;
cout<<"the input number n is:"<<n<<endl;
cout<<"ch:"<<ch<<endl;
return 0;
}
C++ 的cin只输入数字及只输入1、2的代码试验
最新推荐文章于 2023-05-07 19:31:24 发布