【C++】学习笔记二十七——读取数字的循环
来源:互联网 发布:上海万国数据 编辑:程序博客网 时间:2024/05/16 14:17
假设要将一系列数字读入到数组中,并允许用户在数组填满之前结束输入。一种方法是利用cin:
int n;cin >> n;
如果用户输入一个单词而不是数字,将发生:
- n的值保持不变;
- 不匹配的输入将被保留在输入队列中;
- cin对象中的一个错误标记被设置;
对cin方法的调用将返回false。
返回false意味着可以用非数字输入来结束读取数字的循环。非数字输入设置错误标记意味着必须重置该标记,程序才能继续读取输入。clear()重置输入错误标记,同时也重置文件尾(EOF)。输入错误和文件尾都会导致cin返回false。
程序6.13
#include<iostream>const int Max = 5;int main(){ using namespace std; double fish[Max]; cout << "Please enter the weights of your fish.\n"; cout << "You may ennter up to " << Max << " fish <q to terminate>.\n"; cout << "fish #1: "; int i = 0; while (i<Max && cin >> fish[i]) { if (++i < Max) cout << "fish #" << i + 1 << ": "; } double total = 0.0; for (int j = 0; j < i; j++) total += fish[j]; if (i == 0) cout << "No fish\n"; else cout << total / i << " = average weight of " << i << " fish\n"; cout << "Done.\n"; system("pause"); return 0;}
程序6.14
#include<iostream>const int Max = 5;int main(){ using namespace std; //get data int 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(); while (cin.get() != '\n') continue; cout << "Please enter a number: "; } } //calculate average double total = 0.0; for (i = 0; i < Max; i++) total += golf[i]; //report results cout << total / Max << " = average score " << Max << " rounds\n"; system("pause"); return 0;}
在程序6.14中,关键部分如下:
while (!(cin >> golf[i])) { cin.clear(); while (cin.get() != '\n') continue; cout << "Please enter a number: "; }
如果用户输入88,则cin表达式将为true,因此将一个值放到数组中;而表达式!(cin>>golf[i])为false,因此内部循环结束。然而,如果用户输入must i?,则cin表达式将为false,因此不会将任何值放到数组中;而表达式!(cin>>golf[i])将为true,因此进入内部的while循环。该循环的第一条语句使用clear()来重置输入,如果省略这条语句,程序将拒绝读取输入;接下来,程序在while循环中使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。另一种方法是读取到下一个空白字符,这样将每次删除一个单词,而不是一次删除整行。最后程序告诉用户,应输入一个数字。
0 0
- 【C++】学习笔记二十七——读取数字的循环
- 【C++】学习笔记十七——基于范围的for循环
- Objective-C学习笔记(二十七)——方法的重载与重写
- OpenCV学习笔记(二十七)——基于级联分类器的目标检测objdect
- OpenCV学习笔记(二十七)——基于级联分类器的目标检测objdect
- OpenCV学习笔记(二十七)——基于级联分类器的目标检测objdect
- OpenCV学习笔记(二十七)——基于级联分类器的目标检测objdect
- 读取数字的循环
- Object-C 学习笔记(二十七)--- 文件操作(沙盒)
- Nginx学习笔记(十七):master进程的循环工作
- 学习笔记(二十七)
- shell学习二十七--循环控制命令
- c语言学习笔记十七
- 【C++】读取循环数字和cin的利用
- 大数据学习笔记之二十七 Hadoop的HBase
- C#回顾学习笔记二十七:using的两个作用
- php学习笔记(二十七)读取session和删除session
- Delphi的学习笔记十七——Exception处理
- 留言区
- Linux Shell echo
- Excel数据分析与业务建模_第三章_引用函数INDEX(语法详解及应用实例)
- java序列化(Serializable)的作用和反序列化(转)
- 三、Java数组
- 【C++】学习笔记二十七——读取数字的循环
- poj_3411 Paid Roads(dfs技巧)
- IOC前世今生
- PAT. basic level. 1002
- 如何使用Alfred提升操作效率(上)
- [机房考试] 图论
- 苏嵌33 17.01.18
- LINUX ECHO 颜色
- 嵌入式数据结构