读取数字的循环,用cin表达式的值判断错误输入并清除cin流接受新的输入

cin>>fish[i]实际上是一个cin函数的调用,该函数返回cin。如果cin位于测试条件中,则将被转化为bool类型,输入成功则转化后的值为true,否则为false。


不匹配的输入将被留在输入队列中 而且cin对象中的一个错误标记被设置

// practice6-13.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
const int Max = 5;

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	double fish[Max];
	cout<<"Enter the weight of your fish:\n";
	cout<<"You may up to"<<Max<<"fish <enter q to termnate>.\n";
	cout<<"fish #1:";
	int i=0;
	while (i<Max&&cin>>fish[i])
	{
		if (++i<Max)
		{
			cout<<"fish #"<<i+1<<":";
		}
	}
	//calculate average
	double total=0.0;
	for (int j=0;j<i;++j)
	{
		total += fish[j];
	}
	// report results
	if (i==0)
	{
		cout<<"No fish.\n";
	} 
	else
	{
		cout<<"average weight of "<<i<<" fish = "<<total/i<<endl;
	}
	cout<<"Done.\n";
	system("pause");
	return 0;
}


如何让用户改正错误的输入:

1.重置cin以接受新的输入

2.删除错误输入

3.提示用户再输入

注意:程序必须先重置cin,然后才能删除错误输入!

// practice6-14.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
const int Max=5;

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int golf[Max];
	cout<<"Enter your golf sources:\n";
	cout<<"you must enter "<<Max<<" Rounds\n";
	int i;
	for (i=0;i<Max;++i)
	{
		cout<<"Round #"<<i+1<<":";
		while (!(cin>>golf[i]))//如果输入的是数字则结束内部循环
			{
				cin.clear();//重置输入(如果省略这句,程序将拒绝继续读取输入)
		        while(cin.get()!='\n')//读取行尾之前的所有输入,从而删除这一行的错误输入
			       continue;
		        cout<<"Please enter a number:";
		    }
	}
	//average
	double total=0.0;
	for (i=0;i<Max;++i)
	{
		total += golf[i];
	}
	//report results
	cout<<Max<<"Rounds average score = "<<total/Max<<endl;
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值