C++中输入数据类型判断,输入类型错误后,提示用户重新输入直至其输入正确

要求输入number,但是用户键入了字母A,仍然有结果,但是不正确,同时后面的代码自行运行了,没有办法去输入string了。所以要改进,可以判断输入的是否为正确的数据类型

利用cin.good()和cin.fail()判断:

cin.good()为true时,输入的数据类型与定义的数据类型一致

cin.fail()为true时,输入的数据类型与定义的不符。

利用if语句进行判断:

if(cin.fail){

cin,clear();//clear,可重新输入

}

用if语句判断无法循环直至用户输入是对的数据。以下写法只能修改一次,之后就pause了。

int main(){

int iInput;

cin>>iInput;

if(cin.fail()){
        cout<<"Wrong, you have inputed a wrong type data\n"<<endl;
        cin.clear();//清除错误标记,重新打开输入流,但是输入流中依旧保留着之前的不匹配的类型
        /*cin.sync();*///清楚cin缓存区的数据。
        while(cin.get() != '\n'){
            continue;    
        }    
        cout<<"please input again"<<endl;
        cin>>iInput;
    }

return 0;

}

用while可以一直循环

int main(){

int iInput;

cin>>iInput;

while(cin.fail()){
        cout<<"Wrong, you have inputed a wrong type data\n"<<endl;
        cin.clear();//清除错误标记,重新打开输入流,但是输入流中依旧保留着之前的不匹配的类型
        /*cin.sync();*///清楚cin缓存区的数据。
        while(cin.get() != '\n'){
            continue;    
        }    
        cout<<"please input again"<<endl;
        cin>>iInput;
    }

return 0;

}

改进

int main(){

int iInput;

cout<<"please input a number"<<endl;

while(!(cin >> iInput)){
    cout<<"Wrong, you have inputed a wrong type data\n"<<endl;
    cin.clear();//清除错误标记,重新打开输入流,但是输入流中依旧保留着之前的不匹配的类型
    /*cin.sync();*///清楚cin缓存区的数据。
    while(cin.get() != '\n'){
        continue;
    }
    cout<<"please input again"<<endl;
}
    cout<<"The number is: "<<iInput<<endl;
system("pause");
return 0;

}

输入与预期格式不匹配反过来将导致表达式cin>>input的返回值为false,

  • 26
    点赞
  • 108
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值