chapter 17

Chapter 17 Input,Output,and Files

#
# An Overview of C++ Input and Output
#

# Streams and Buffers

An input stream needs two connections, one at end. The
file-end connection provides a source for the stream,
and the program-end connection dumps the stream outflow
into the program. Similarly, managing output.

A buffer is a block of memory used as an intermediate,
temporary storage facility for the transfer of infor-
mation from a device to a program or from a program to
a device.

# The streambuf class provides memory for a buffer.
# The ios_base class represents general properties of
a stream.
# The ios class is based on ios_base,and it includes a
pointer member to a streambuf object.
# The ostream and istream classes derive from the ios.
# The iostream class is based on the istream and ostream
and thus inherits both input and output methods.

When includes the iostream file in a program, Eight str-
eam objects are created:
+ cin object and wcin object
+ cout and wcout objects
+ cerr and wcerr : stream is unbuffered which means
that information is sent directly to screen,without
waiting for a buffer to fill or for a newline.
+ clog and wclog : corresponds to standard error str-
eam. All same with cerr, except that clog stream is
buffered.

# Redirection ( < and > )

#
# Output with cout
#

The ostream class translates the internal representa-
tion of data as binary bit paatterns to an output
stream of character bytes.

# The overloaded << Operato //called insertion operator

# Output and Pointers (page 1070)
The ostream class defines insertion operator functions
for the following pointer types:
+ const signed char *
+ const unsigned char *
+ cosnt char *
+ void *
the method use the terminating null character in the
string to determine when to stop displaying characters

* C++ matches a pointer of any other type with void *
and prints a numeric representation of the address.
If you want the address of the string, you have to
type cast it to another type:

int eggs = 12;
char * amount = "dozen";
cout << &eggs; //prints address of eggs variable
cout << amount; //print the string "dozen"
cout << (void *) amount; //prints the address of dozen string

# Output Concatenation

# The Other ostream Methods
Besides the various operator<<() functions, the
ostream class provides the put() method for dis-
playing characters and the write() method for
displaying strings.

osteram & put(char); //prototype
cout.put(‘W‘).put(‘I‘); //display W,I characters
cout.put(65); //displaying A character
cout.put(66.3); //displaying B character

basic_ostream<charT,traits>& write(const
Char_type * s,streamsize n);
the first argument to write provides the address
of the string to be displayed,and the second
argument indicates how many characters to display.

# Flushing the Output Buffer

Sending a newline character to the buffer to flushes
: flush and endl manipulators.

cout << "Hello, good-looking!" << flush;
//flush(cout) same action
cout << "Wait just a moment,please." << endl;
# Formatting with cout
By default:
+ Char value : one character wide
+ Numeric integer: just wide enough to hold
+ String: equal in width of the length of string
for floating-point types:

+ New style:
with total of 6 digits, trailing 0 aren‘t dis-
played. The number is displayed in fixed-point
notation or else in E notation, depending on the
value of the number. In particular, E notation is
used if the exponent is 6 or larger or -5 or
smalaer.
+ Old style:
are displayed with six places to the right of the
decimal,except the trailing zeros aren‘t displayed

# Changing the Number Base Used for Display

The ostream class inherits from the ios class,which
inherits from the ios_base class. By using ios_base
member functions, can control the field width and the
number of places displayed to the right of the decimal
...
note:
*****************************************************
in the new system,ios is a template class with
char and wchar_t specializations,and ios_base contains
the nontemplate features.
******************************************************

to control integers are displayed in base 10,16,8, you
can use the dec,hex,and oct manipulators. for example:

hex(cout);cout<<233;
or:
cout << hex << 12334;

the manipulators are in the std namespace.
# Adjusting Field Widths

You can use the width member function to place differ-
ently sized numbers in fields that have equal widths.
the method has these prototypes:

int width(); // returns the current setting
int width(int i);//return the previous field width

*** Caution:
The width() method affects only the next item dis-
played,and the field width revert to the default
value afetward.

The character used for padding is termed "fill
character",Right-justification is the default.

# Fill Characters
By default, cout fills unused parts of a field with
spaces.You can use the fill() member function to
change that.

cout.fill(‘*‘);

note that, unlike the field width, the new fill chara-
cter stay in effect until you change it.

# Setting Floating-point Display Precision

In the default mode, it means the total number of
digits displayed.
In the fixed and scientific modes, precision means the
number of digits displayed to the right of decimal
place. The precision default for C++ is 6.

The precision() member function do the job:

cout.precision(2);

The effect stays the same until it is reset.

# Printing Trailing Zeros and Decimal Points

The ios_base class provides a setf() (for set flag)
function. The class also defines several constants
that can be used as arguments to this function:

cout.setf(ios_base::showpoint);
//display trailing decimal points.
# More About setf()

The setf() function has two prototypes:

1, fmtflags setf(fmtfalgs);

fmtflags is a typedef name for a bitmask type
which is defined in the ios_base class. The return
value is the former setting of all the flags.

ios_base::boolalpha, iso_base::showbase
ios_base::showpoint, iso_base::uppercase
ios_base::showpos # (page 1085)

2, fmtflags setf(fmtflags, fmtflags );

The first argument is as before that contains the
desired setting.
The second argument is a value that first clears
the appropriate bits (eg, set first unset second)

cout.setf(ios_base::hex,ios_base::basefield);
######################################################
Table 17.2 Argument for setf(long, long) (page 1087)

Second Argument First Argument Meaning
ios_base::basefield ios_base::dec use base 10
ios_base::oct
ios_base::hex
ios_base::floatfield ios_base::fixed use fix-point
iso_base::scientific
ios_base::adjustfield ios_base::left use left_justi
ios_base::right fication
ios_base::internal
//left-justify sign or base
//prefix,right-justify value
#####################################################

The effects of calling setf() can be undone with
unsetf():
void unsetf( fmtflags mask);
Here mask is a bit pattern. All bits set to 1 in mask
cause the corresponding bits to be unset.

cout.set(ios_base::showpoint);
cout.unset(ios_base::showpoint);
cout.setf(ios_base::boolalpha);
cout.unsetf(ios_base::boolalpha);//display 1,0

Any combination,such as no bits set or both bits set,
results in the default mode being used.so:
cout.setf(0,ios_base::floatfield); //will default
or:
cout.unsetf(ios_base::floatfield); //default

# Standard Manipulators
Using setf() is not the most user-friendly approach to
formatting,so C++ offers several manipulators to invo-
ke setf().such as dec,hex,oct.

Table 17.3 Some Standard Manipulators
---------------------------------------
Manipulator Calls

boolalpha setf(ios_base::boolalpha)
noboolalpha unsetf(ios_base::boolalpha)
showbase setf(ios_base::showbase)
noshowbase
showpoint
noshowpoint
showpos
noshowpos
uppercase
nouppercase
internal setf(ios_base::internal,
ios_base::adjustfield)
left
right
dec
hex
oct
fixed
scientific setf(ios_base::scientific,
ios_base::floatfield)
---------------------------------------------

# The iomaip Header File

Setting some format values,such as the field width,
can be awkward using the iostream tools. To make life
easier,C++ supplies additional manipulators in the
iomanip header file providing the same services.

setprecision(),setfill(),setw //field width.

#
# input with cin
#
A typical operator function has a prototype like:

istream & operator>>(int &);

You can use the hex,dec,oct manipulators with cin
to specify that integer input is to be interpreted
as hexadecimal,octal,or decimal format.

for example:
cin >> hex >> x;
# How cin >> Views input

It reads everything from the initial non-white-space
character up to the first character that doesn‘t match
the destination type.
int evlevation;
cin >> evlevation;
Suppose you type the following characters:
-123G
then read -123 and the G will be remained in stream.

# Stream states

A cin or cout object contains a data member(inherited
from the ios_base class)that describles the stream
state. A stream state(defined as type iostate,which,in
turn,is a bitmask types) consists of the three ios_
base elements: eofbit,badbit,and failbit.Each element
is a single bit that can be 1 or 0.

I/O failures also set failbit.
The badbit is set when someundiagnosed failure may
have corrupted the stream.

When all three of these state bits are set 0,everyting
is fine.

Table 17.4 Stream State
---------------------------------------------------------
Member Description

eofbit Is set to 1 if end-of-file reached
badbit Is set to 1 if the stream may be corrupted;
for example: a file read error.
failbit Is set to 1 if an input operation failed to
read the expected characters or an output
operation failed to write the expected charac-
ters.
goodbit Just another way of saying 0;
good() Return true if the stream can be used(all bits
are cleared).
eof() Returns true if eofbit is set
bad() Returns true if badbit is set
fail() Returns true if badbit or failbit is set
rdstate() Returns the stream state.

exceptions() Returns a bit mask that identifies which
flags cause an exception to be thrown.

exception(iostate ex) Sets which states will cause
clear() to throw an exception; for example,
if ex is eofbit,then clear() will throw an
exception if eofbit is set

clear(iostate s) Set the stream state to s;the default
for s is 0(goodbit);throws a basic_ios::fail-
ure exception if rastate() & exceptions() != 0

setstate(iostate s) Calls clear(rdstate() | s).This sets
stream state bits corresponding to those bits
set in s;other stream state bits are left un-
changed.
----------------------------------------------------------
# Setting States

clear();//default 0. clear all three state bits
clear(eofbit); //set eofbit and clear badbit,failbit.

setstate() method affects only those bits that are set
in its argument.

setstate(eofbit); //badbit,failbit no change

# I/O and Exceptions

Changing the stream state invovles either clear() or
setstate(),which uses clear(). After changing the str-
eam state, the clear() method compares the current s-
tream state to the value returned by exception().If a
bit is set in the return value and the corresponding
bit is set in the current state,clear() throws an ios_
base::failure exception.This would happen,for example
,if both values had badbit set.

The default setting for exception() is goodbit--that
is,no exceptions thrown. The overloaded
exceptions(iostate)function gives you control over the
behavior:

cin.exceptions(badbit);
cin.exceptions(badbit | eofbit);

# Stream State Effects

An if or while test such as the following tests as
true only if the stream state is good(all bits cleared
) :
while (cin >> input)

If you want a program to read further input after a
stream state bit has been set,you have to reset the
stream state to good. by using clear() method:

cin.clear();
while (!isspace(cin.get())
continue;
cin >> input;

# Other istream Class Methods

The get(char &) and get(void) single-character input
The get(char *,int,char) and getline(char *,int,char)
functions by defult read entire lines rather than
single words.

# Single-Character Input (page 1103)

char c1,c2,c3;
cin.get(c1).get(c2) >> c3;

The method calls setstate(failbit),which causes cin to
test as fales:

char ch;
while (cin.get(ch))
{
//process
}

char ch;
ch = cin.get();
while(ch != ‘\n‘) { ... }

get(void) member function return int or larger,so can
not do like this:
cin.get().get() >> c3; //not valid
Upon reaching the end-of-file,cin.get(void) returns
the value EOF:
int ch;
while((ch = cin.get()) != EOF) { ... }

# Which Form of Single-Character Input to Use?

If skipping white space is convenient, should use >>

If examine every character, should use one of the
get() methods.

# String Input: getline(),get(),and ignore()

istream & get(char *,int,char);
istream & get(cahr *,int);
istream & getline(char *,int,char);
istream & getline(char *,int);

The first argument is the address of the location to
place the input string. The second argument is one
greater than the maximum number of characters to be
read. The third argument specifies a character to act
as a delimiter.

Each function reads up to the maximum characters or
until it encounters the delimiter character, which-
ever comes first. for example:

char line[50];
cin.get(line,50); // read 49 characters

The chief difference between get() and getline() is
that getline() extracts and discards the newline cha-
racter from the input stream.

ignore() member function takes two arguments: a num-
ber specifying a maximum number of characters to read
and a character that acts as a delimiter character.

For example,the following function call reads and
discards the next 255 characters or up through the
first newline character,whichever comes first:
cin.ignore(255,‘\n‘);

The prototype is :

istream & ignore(int = 1, int = EOF);

# Unexpected String Input

Two other special cases are no input and input that
meets or exceeds the maximum number of characters
specified by the function call.

If either method fails to extract any characters,the
method places a null character into the input string
and uses setstate() to set failbit.

Table 17.6 Inpput Behavior
------------------------------------------------------
Method Behavior

getline(char *,int) Sets failbit if no characters are
read(but newline counts as a cha-
racter read).
Set failbit if the maximum number
of characters are read and more
are still left in the line.

get(char *,int) Sets failbit if no characters are
read.
-------------------------------------------------------

# Other istream Methods

So far include read(),peek(),gcount(),and putback().

char gross[144];
cin.read(gross,144); //144 is number of bytes

The peek() function returns the next character from
input without extracting from the input stream.

The gcount() method returns the number of characters
read by the last unformatted extraction method.That
means characters read by a get(),getline(),ignore,or
read() method but not by the extraction operator(>>),
which formats input to fit particular data types.
cin.gcount();

The putback() function inserts a character back in the
input string.The inserted character then becomes the
first character read by the next input statement:

istream & putback(char);
#
# File input and output
#
To help handle these tasks, c++ defines several new
classes in the fstream header file, including the
ifstream class for file input and the ofstream class
for file output. C++ also defines the fstream class
for simulataneous file I/O.

# Simple File I/O

ofstream fout;
fout.open("jar.txt"); //ofstream fout("jar.txe");
fout << "Dull Data"; //put the words into the file.

ifstream fin;
fin.open("jellyjar.txt");
or:
ifstream fin("jellyjar.txt");

char ch;
fin >> ch; //read a character from the file

char buf[80];
fin >> buf; //read a word from the file
fin.getline(buf,80);
string line;
getline(fin,line); //read from a file to a string

The connections with a file are closed automatically
when the input and output stream objects expire.
Also can close a connection with a file explicitly by
using the close() method;

fout.close(); fin.close();

# Stream Checking and is_open()

if (!fin.is_open()) // open attempt failed

In the past:

if(fin.fail())
if(fin.good())
if(!fin)

# Opening Multiple Files

# Command-Line Processing

int main( int argc, char * argv[])

# File Modes

The file mode describes how a file is to be used:
read it, write to it, append it, and so on.

ifstream fin("banjo",mode1);
ofstream fout();
fout.open("harp",mode2);

The ios_base class defines an openmode type to repre-
sent the mode;like the fmtflags and iostate types,it
is a bitmask type.You can choose from several cons-
tants and their meanings.

Table 17.7 File Mode Constants (page 1122)
------------------------------------------------------
Constant Meaning

ios_base::in Open file for reading
ios_base::out Open file for writing.
ios_base::ate Seek to end-of-file upon opening file
ios_base::app Append to end-of-file.
ios_base::trunc Truncate file if it exists.
ios_base::binary Binary file.
------------------------------------------------------

for example:

ofstream fout("bagels",ios_base::out | ios_base::app);

# Binary Files

ofstream fout("planets.dat",ios_base::out |
ios_base::app | ios_base::binary);
fout.write( (char *) &pl,sizeof pl); //pl is structure

ifstream fin("planet.dat",ios_base::in |
ios_base::binary);
fin.read( (char *) &pl,sizeof pl);

If the class does have virtual methods,then a hidden
pointer to a table of pointers to virtual functions
is also COPIED.

# Random Access

To random accesses a file, the file‘s open mode:
ios_base::in | ios_base::out | ios_base::binary

seekg(): moves the input pointer to a given file
location.
seekp(): moves the output pointer to a given file
location.

basic_istream<charT,trait>& seekg(off_type,
ios_base::seekdir);
basic_ostream<charT,traits>& seekp(pos_type);

istream & seekg(streamoff,ios_base::seekdir);
istream & seekg(streampos);

The first prototype represents locating a file posi-
tion measured,in bytes,as an offset from a file loca-
tion specified by the second argument.

The second prototype represents locating a file posi-
tion measured,in bytes,from the beginning of a file.

seekdir includes the threes:
ios_base::beg ios_base::cur ios_base::end

for example:
fin.seeg(-1,ios_base::cur); //back up one byte

You can treat a streampos position as if it measures
a file location in bytes from the beginning of a file
,with the first byte being byte 0.

fin.seekg(112) //locates the 113th byte

tellg() and tellp() methods can find the position of
a file pointer for input stream and output stream
respectively.

fstream finout; // read and write streams
finout.open(file,ios::in | ios::out | ios::binary);

if(finout.is_open())
finout.seekg(0); //go to beginning

if(finout.eof())
finout.clear(); //clear eof flag, reuse file.

streampos place = rec * sizeof pl; //covert to bytes
finout.seekg(place);
finout.seekp(place);
finout.write((char *) &pl,sizeof pl) << flush;

#
# Incore Formatting
#
The iostream family supports I/O between a program
and a terminal.The fstream family uses the same in-
terface to provide I/O between a program and a file.
The C++ library also provides an sstream family,which
uses the same interface to provide I/O between a pro-
gram and a string object.

The process of reading formatted information from a
string object or of writing formated information to
a string object is termed "INCORE FORMATTING".

The sstream header file defines an ostringstream
class that is derived from the ostream class.

ostringstream outstr;
double price = 380.0;
char * ps = " for a copy of the C++ standard";
outstr.precision(2);
outstr << fixed;
outstr << "Pay only CHF " << price << ps << endl;

string mesg = outstr.str(); //return string with
formatted information
Using the str() method "freezes" the object,and can
no longer write to it.

istringstream instr(facts); //facts is a string
object and use it to initialize stream

while (instr >> n)
......

In short, the istringstream and ostringstream classes
give you the power of the istream and ostream class
methods to manage character data stored in strings.

时间: 2024-10-04 12:47:28

chapter 17的相关文章

Chapter 17. Objects and Inheritance(对象与继承)

SELECT DISTINCT fa.application_short_name 模块,                 b.responsibility_name 职责名称, fa.application_name 应用产品,                 b.responsibility_key 责任关键字, b.description 说明,                 DECODE (b.data_group_id, 0, '标准', '') 数据组,              

零元学Expression Blend 4 - Chapter 17 用实例了解互动控制项「CheckBox」I

原文:零元学Expression Blend 4 - Chapter 17 用实例了解互动控制项「CheckBox」I 本章将教大家如何运用CheckBox做实作上的变化:教你如何把CheckBox变藏宝箱! ? 本章将教大家如何运用CheckBox做实作上的变化:看我怎麽把CheckBox变藏宝箱! ? 最近帮公司做了一个互动式的小游戏,运用了CheckBox的功能,就顺便介绍给大家 为了利益回避,以及日後不必要的麻烦,本章范例已经简化了很多东西,只留下与相关的图片及功能 ? 01 先简单介绍

Head first java chapter 17 包、jar存档文件和部署

数据库 chapter 17 数据仓库与联机分析处理技术

第十七章 数据仓库与联机分析处理技术 计算机系统中存在着两类不用的数据处理工作:操作型处理和分析型处理,也称作OLTP(联机事务处理)和OLAP(联机分析处理) 操作型处理是指对数据库联机的日常操作,通常是对一个或一个组记录的查询和修改. 分析型处理是指对数据的查询和分析操作,通常是对海量的历史数据查询和分析. 据(即多维数据)到底存储在什么地方,是怎么存储的.OLAP服务器则必须考虑物理上这些数据的存储问题. 前台工具包括查询报表工具.多维分析工具,数据挖掘工具和分析结果可视化工具等. 联机分

Chapter 17 Autorotation, Popover Controller, and Modal View Controllers

1.There are two distinct orientations in iOS: device orientation and interface orientation. The device orientation represents the physical orientation of the device, whether it is right-side up, upside down, rotated left, rotated right, on its face,

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

CHAPTER 1 Introduction to database (第一章 数据库简介)

Chaper  Objectives  (章节目标) In this chapter you will learn:   (在这一章节中,你将学习) 1. Some common uses of database systems.   (数据库系统的一些普通扩法) 2.The characteristics of file-based systems. (基于文件系统的一些特点.) 3. The problems with the file-based systems.  (基于文件系统拥有的一

JVM Specification 9th Edition (2) Chapter 1. Introduction

Chapter 1. Introduction 翻译太累了,我就这样的看英文吧. 内容列表 1.1. A Bit of History 1.2. The Java Virtual Machine 1.3. Organization of the Specification 1.4. Notation 1.5. Feedback 1.1. A Bit of History The Java? programming language is a general-purpose, concurrent

读《构建之法》4、17章所思所感

仅针对这2章的阅读,主要讲的是团队之间,不仅是2人之间的,更是整个团队在完成一个项目.在一起工作时需要的各方面的力量,也有对领导力.绩效以及职业道德方面的讲述. 以下就是我在读完1.2.16章后的一些问题和感想. Chapter 4 两人合作 查尔斯·塔列朗说:"比起由一只羊领导的一百头狮子,我更害怕由一头狮子领导的一百只羊."如果自己要想有所作为,那就需要提升自己,提高影响力:如果在力所能及的范围内想帮助别人提升其价值,那也即帮助他们挺高影响力,让自己和队友通过相互想影响,提升技能.