C++ 的cin只输入数字及只输入1、2的代码试验


//*********************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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值