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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yxswhy/article/details/82867875

要求输入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,

猜你喜欢

转载自blog.csdn.net/yxswhy/article/details/82867875