C++编程积累——解决cin>>num输入问题,cin无效,无法从屏幕输入(cin状态清除)

问题描述

有时候会遇到这样的问题:

想要从屏幕输入值(cin>>num,num是int类型变量),来对输入值进行处理。但在实际运行中,输入操作却被忽略了,无法进行输入操作。但整个程序又没有语法类问题

如下边下边例子,是对一串数字进行二分查找某个特定值:

程序过程:

1、从屏幕输入一串有序数字,放入一个vector对象中

2、从屏幕输入一个特定值,在vector对象中进行二分查找此特定值,如果存在,输出此特定值,如果不存在,输出“the number is not existed”

# include<iostream>
# include<fstream>
#include<string>
#include<vector>
using namespace std;
int main()
{
    vector<int> ivec;
    int num;
    //输入数字
    cout << "Please enter the number in sequence" << endl;
    while (cin >> num)
        ivec.push_back(num);

    cout << "Please enter the number that you will look:" << endl;
    int number;
    cin >> number;
    auto beg = ivec.begin();
    auto mid = ivec.begin() + ivec.size() / 2;
    auto end = ivec.end();
    int k = 0;
    while (mid != end)
    {
        if (*mid > number)
        {
            end = mid;
            mid = beg + (end - beg) / 2;
        }
        else if (*mid < number)
        {
            beg = mid+1;
            mid = beg + (end - beg) / 2;
        }
        else
        {
            cout << "the number is: " << *mid << endl;
            k++;
            break;
        }

    }
    if (k == 0)
        cout << "the number is not existed"<<endl;

    return 0;

}

 运行结果如下,cin>>number操作直接被忽略了!!!!!!


解决方法 

出现的原因:

cin >> number;通常情况会进行输入读取一个数值,前提是cin正常。如果cin被核定为false,则cin就不会被执行啦。

上述例子中,因为我们在输入一串数字时,输入了结束符进行退出,所以cin已经被核定为false了,所以下边的cin>>number无法正常执行输入操作。

解决方法:

我们要对cin进行恢复,使其恢复正常状态。使用cin.clear()和cin.sync()可以恢复正确状态

补充:

cin被核定为false的情况:(1)遇到结束符:(2)无效输人


通过对上述cin进行恢复如下,一切运行正常:

# include<iostream>
# include<fstream>
#include<string>
#include<vector>
using namespace std;
int main()
{
    vector<int> ivec;
    int num;
    //输入数字
    cout << "Please enter the number in sequence" << endl;
    while (cin >> num)
        ivec.push_back(num);
    
    // 恢复cin正常状态,两个一起使用
    cin.sync();   //清除缓冲区
    cin.clear();  //清除错误状态

    cout << "Please enter the number that you will look:" << endl;
    int number;
    cin >> number;
    auto beg = ivec.begin();
    auto mid = ivec.begin() + ivec.size() / 2;
    auto end = ivec.end();
    int k = 0;
    while (mid != end)
    {
        if (*mid > number)
        {
            end = mid;
            mid = beg + (end - beg) / 2;
        }
        else if (*mid < number)
        {
            beg = mid+1;
            mid = beg + (end - beg) / 2;
        }
        else
        {
            cout << "the number is: " << *mid << endl;
            k++;
            break;
        }

    }
    if (k == 0)
        cout << "the number is not existed"<<endl;

    return 0;

}

执行结果:

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值