读取数字的循环

来源:互联网 发布:开淘宝店经验 编辑:程序博客网 时间:2024/05/22 02:30
假设要编写一个将一系列数字读入到数组的程序,并准许用户在数组填满之前结束输入。一种方法是利用cin。请看下面的代码:

int n;cin>>n;

如果用户输入一个单词,而不是一个数字,情况将如何呢?发生这种类型不匹配的情况时,将发生4中情况:

n的值保持不变

不匹配的输入将被留在输入队列中

cin对象中的一个错误标记被设置

对cin方法的调用将放回false(如果被转换为bool类型)

例子:

#include <iostream>const int Max = 5;int main(){using namespace std;// get datadouble fish[Max];cout<<"Please enter the weights of your fish.\n";cout<<"You may enter up to "<<Max<<" fish <1 to terminate>.\n";cout<<"fish #1: ";int i=0;while(i < Max && cin>>fish[i]){if(++i<Max){cout<<"fish #"<<i+1<<": ";}}// calculate averagedouble total = 0.0;for(int j =0; j<i; j++){total += fish[j];}// report resultsif(i==0){cout<<"No fish\n";}else{cout<<total/i<<" = average weight of "<<i<<" fish\n";}cout<<"Done.\n";return 0;}

运行结果:

Please enter the weights of your fish.You may enter up to 5 fish <1 to terminate>.fish #1: 30fish #2: 35fish #3: 25fish #4: 40fish #5: q32.5 = average weight of 4 fishDone.Press any key to continue

再看个例子,程序要求用户提供5个高尔夫得分,以计算平均成绩。如果用户输入非数字输入,程序将拒绝,并要求用户继续输入数字。可以看到,可以使用cin输入表达式的值来测试输入是不是数字。程序发现用户输入了错误的内容时,应采取3个步骤:

重置cin以接受新的输入。

删除错误输入。

提示用户再输入。

代码:

// cingolf.cpp -- non-numeric input skipped#include <iostream>const int Max = 5;int main(){using namespace std;// get dataint golf[Max];cout<<"Please enter your golf scores.\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();// reset inputwhile(cin.get()!='\n'){continue;// get rid of bad input}cout<<"Please enter a number: ";}}// calculate averagedouble total = 0.0;for (i=0; i<Max; i++){total += golf[i];}cout<<total/Max<<" = average score "<<Max<<" rounds\n";return 0;}

运行结果:

Please enter your golf scores.You must enter 5 rounds.round #1: 88round #2: 87round #3: must i?Please enter a number: 103round #4: 94round #5: 8691.6 = average score 5 roundsPress any key to continue






原创粉丝点击