题目:读取数字的循环。
内容:使用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 }

 

相关文章:

  • 2022-12-23
  • 2021-04-13
  • 2021-06-27
  • 2022-12-23
  • 2021-09-18
  • 2021-07-05
  • 2021-12-31
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2021-05-30
相关资源
相似解决方案