读取数字的循环
来源:互联网 发布:开淘宝店经验 编辑:程序博客网 时间:2024/05/22 02:30
假设要编写一个将一系列数字读入到数组的程序,并准许用户在数组填满之前结束输入。一种方法是利用cin。请看下面的代码:
如果用户输入一个单词,而不是一个数字,情况将如何呢?发生这种类型不匹配的情况时,将发生4中情况:
运行结果:
运行结果:
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
- 读取数字的循环
- 【C++】读取循环数字和cin的利用
- 读取在一定范围内的数字
- 【C++】学习笔记二十七——读取数字的循环
- 一组数字的循环输出
- 读取数字的循环,用cin表达式的值判断错误输入并清除cin流接受新的输入
- 读取数据库的死循环
- 循环读取Map的数据
- 快速读取的数字函数
- 读取数字循环(遇非数字退出和跳过继续读取两种情况C++代码)
- 数字读取
- 一个将数字循环移动的问题
- iterator 的遍历 循环输出数字,页码
- 关于lua数字for循环的实现
- java版的双重循环数字金字塔
- 循环中读取数据库、嵌套循环引起的性能问题
- Web 下dataReader的循环读取
- 循环读取重名节点的方法
- C++中抽象类和接口类的区别
- 自定义UITableViewCell,实现类似QQ好友列表
- ThinkPad T61风扇转速控制方法
- 编程语言
- TableCell自适应表格高度
- 读取数字的循环
- void与void*指针
- omap移植systemtap
- C++类别转换之char*与CString的互转换
- 文件I/O
- throw &throws
- C++ typedef用法小结
- ubuntu下安装memcache
- 求质数因子