Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

10.7 读取单个值

现在我们已经知道如何读取以文件尾或者某个特定终结符结束的值序列了。我们还会学习一些更为复杂的例子,但在此之前,先来看一个非常常见的应用问题:不断要求用户输入一个值,直至用户输入的值合乎要求为止。这个例子允许我们检验几种常见的设计策略,我们通过“如何从用户获取一个合乎要求的值”这个问题的几种可选的解决方案来讨论这些设计策略。我们从一个不那么令人满意的“初步尝试”方案开始,逐步提出改进方案。基本假设是:我们是在处理交互式的输入——程序给出提示信息,用户键入数据。假定我们要求用户输入一个1到10之间(包含1和10)的整数:

这段代码确实很“丑陋”,但它在某种程度上是能正常运行的。如果你不喜欢使用break(参见附录A.6),可以将读操作和范围检查合并为一条语句:

这不过是简单的改头换面,并未改变代码的实质。为什么说这段代码只是“某种程度上能正常运行”的呢?原因在于,这段代码只有在用户很小心地输入整数的情况下才正常运行。如果用户用键盘输入很不熟练,本想输入6,但输入了t(在大多数键盘上,t恰好在6的下面),程序会不改变n的值就退出循环,于是n中的值就不在要求范围之内。这样的代码是不能被称为高质量代码的。而且,爱开玩笑的人(或者是勤奋的测试人员)还有可能从键盘键入“文件尾”符号(在Windows平台是Ctrl+Z,在Unix平台是Ctrl+D)。于是,再次出现循环结束后n不在合法范围的情况。换句话说,为了获得可靠的输入,我们必须处理三个问题: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252