Skip to Content
C++语言导学(原书第2版)
book

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

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

10.3 输入

在<istream>中,标准库提供了istream来实现输入。与ostream类似,istream处理内置类型的字符串表示形式,并能轻松地扩展对用户自定义类型的支持。

运算符>>(“从…获取”)实现输入功能;cin是标准输入流。>>右侧的运算对象决定了输入什么类型的值,以及输入的值保存在哪里。例如:

这段代码从标准输入读取一个数,如1234,保存在整型变量i中。然后读取一个浮点数,如12.34e5,保存在双精度浮点型变量d中。

类似于输出操作,输入操作也可以链接起来,所以上面的代码也可等价写成:

两段代码执行的时候,都是在读到非数字字符时终止整型数的读取。默认情况下,>>会跳过起始的空白符,因此一个完整输入序列可能是下面这样的:

我们常常要读取一个字符序列,最简单的方法是读入一个string。例如:

如果你键入Eric,程序将回应:

默认情况下,空白符,如空格或换行,会终止输入。因此,如果你键入Eric Bloodaxe冒充不幸的约克王,程序的回应仍会是:

你可以用函数getline()来读取一整行(包括结束的换行符),例如: ...

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280