碰到输入错误时,如何清除错误输入,接受正确输入

来源:互联网 发布:阿里云静态资源库 编辑:程序博客网 时间:2024/05/29 13:16

实例: 输入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;

0 0