cin输入错误时导致failbit为1时的缓冲区分析。

//当cin尝试将输入的字符读为int型数据失败后,会产生一个错误状态

//会把cin的failbit设定为1,所以会出现cin错误。所以must i?

//依然会留在缓冲区中(由此我们可以做一个假定当输入触发cin中的failbit

//为1时,数据仍然留在缓冲区中并没有被丢弃)

//要使程序能够继续正常工作需要用clear清除failbit状态

#include <iostream>
using namespace std;
const int Max = 5;
int main()
{
	
	//using namespace std;
	//get data
	int golf[Max];
	cout<< "Please enter your golf scores.\n";
	cout << "you must enter " << Max << " round.\n";
	int i;
	for (i = 0; i < Max; i++)
	{
		cout << "round # " << i + 1 << ": ";
		while (!(cin>> golf[i]))
		{
			cin.clear();
			char ch;
			while ((ch=cin.get()) != '\n')
			{
				cout << ch << "Look!\n";
				continue;
			}
			cout << "Please enter a number: ";
		}
	}

	double total = 0.0;
	for (i = 0; i < Max; i++)
		total += golf[i];

	cout << total / Max << " = average score " << Max << " rounds\n";

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值