实例: 输入5个高尔夫得分, 计算平均值,每次输入需为正整数
#include <iostream>
const int MAX = 5;
using namespace std;
int main()
{
int golf[MAX];
double total = 0;
cout << "Please enter your golf scores.\n";
cout << "You must enter 5 rounds.\n";
for(int 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: ";
}
}
for(int i = 0; i < MAX; i++)
total += golf[i];
cout << total/MAX << " = average score " << MAX << " rounds" << endl;
return 0;
}
在上例中,我们需要输入的是整数类型,如果输入错误类型,需要经过三步来接受新的输入:
①重置cin接受新的输入 cin.clear();
②删除错误输入 while(cin.get() != '\n')
continue;
③提示用户再输入 cout << "Please enter a number" << endl;