c++学习笔记(cin输入类型不匹配的问题)

题目:读取数字的循环。
内容:使用cin输入数字,当发生类型不匹配的情况如何处理。
要求:如果用户输入非数字输入,程序将拒绝,并要求用户继续输入数字。
步骤:程序发现用户输入了错误内容时,应采取3个步骤:
               1.重置cin以接受新的输入(cin.clear();)。
               2.删除错误输入。
               3.提示用户再输入。

 1 #include <iostream>
 2 const int Max=5;
 3 int main()
 4 {
 5     using namespace std;
 6     int golf[Max];
 7     cout<<"Please enter your golf scores.\n";
 8     cout<<"You must enter "<<Max<<" rounds.\n";
 9     int i;
10     for(i=0;i<Max;i++)
11     {
12         cout<<"round #"<<i+1<<":";
13         while(!(cin>>golf[i])){
14             cin.clear();         //重置cin
15             while(cin.get()!='\n')         //删除错误输入
16                 continue;
17             cout<<"Please enter a number: ";  //提示用户再输入
18         }
19     }
20     double total=0.0;
21     for(i=0;i<Max;i++)
22         total+=golf[i];
23     cout<<total/Max<<"=average score "<< Max <<" rounds\n";
24     return 0;
25 }

 

posted @ 2019-09-24 23:06  草叶321  阅读(1600)  评论(0编辑  收藏  举报