条件状态

本文介绍如何在C++中检查与处理cin流的状态,包括设置与清除错误标志,以及在读取输入时应对各种错误情况的方法。通过实例展示了如何在遇到bad或fail状态时进行错误恢复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>

using namespace std;


void check_cin_state(istream& is)
{
    if (is.bad())//检查cin是否坏了
        cout << "cin ban()" << endl;
    else
        cout << "cin is not  bad" << endl;

    if (is.fail())//cin输入字符而且不能转化为数字
        cout << "cin fail()" << endl;
    else
        cout << "not fail" << endl;
}


int main()
{
    cout << "检查cin的状态" << endl;

    cin.setstate(istream::badbit);//强制设置流的状态
    cin.setstate(istream::badbit | istream::failbit);//同时设置两个位
    cin.clear(istream::badbit);//清除某一个
    cin.clear()://全清除

    //cin.eof()//end of file是否结束,ctrl+z结束符
    //cin.good 只要不是bad和fail。出现任何问题不是good
    check_cin_state(cin);
    /*int n;
    cin >> n;
    cout << "'=" << endl;
    check_cin_state(cin);*/
    /*int sum = 0, value;
    while (cin >> value)
    {
        sum += value;
        cout << "sumn;" <<sum<< endl;
    }
*/
    istream::iostate old_state = cin.rdstate();
    //使用流之前把流的状态保存下来,用完后恢复
    cin.clear(old_state);
    int sum = 0, value;
    while (cin >> value, !cin.eof())
    {
        if (cin.bad())
            throw std::runtime_error("IO IS  BAD");
        if (cin.fail())
        {
            cerr << "bad data " << endl;
            cin.clear();//恢复流的正常状态
            cin.ignore(200,'\n');//错误的数据都清除掉
            continue;//回到循环继续下一个数字
        }
        sum += value;
        cout << "sun is" <<sum<< endl;
    } 

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值