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;
}