Chapt 13. Input and Output (I/O)

13.1. Input and Output (I/O) streams: (Learn C++)

I. Introduction

Basically, I/O in C++ is implemented with streams

Abstractly, stream is just a sequence of characters can be accessed directly

II. Abstraction

A. input stream

used to hold input from a data producer i.e. keyboard, network, file

B. output stream

used to hold output for a data consumer i.e. printer, monitor, file

∗ dont need to know how streams intract with actual devices, left up to OS

III. I/O Classes

‘ios’ is base class of both input and output streams, and inherited from ‘ios_base’

A. ‘istream'(>>)

primary class used for input stream. the extraction operator(>>) is used to remove value from the stream

B. ‘ostream'(<<)

primary class used for output stream. the insertion operator(<<) is used to insert value into the stream

∗ ‘_withassign’, stream classes wont be handled directly

I/O Class Hierarchy (Learn C++)

IV. standard streams

pre-created and connected stream object for a program by its environment

A. ‘cin’: object of istream_withassign class for standard input

B. ‘cout’: object of ostream_withassign class for standard output

C. ‘cerr’: object of ostream_withassign class for standard error, unbuffered

D. ‘clog’: object of ostream_withassgn class for standard error, buffered

∗ unbuffered: processed directly ↔ buffered: temporary stored and processed

13.2. Input with stream: (Learn C++)

∗ all of the I/O objects and functionality prefixed with ‘std’ namespace

I. manipulator:setw()

limit # of bytes read in from the stream for each call

II. extraction operator: ‘>>’

• C++ has predefined extraction operator for all of built-in data types

• Discard white-space(i.e. blank, tab, newline) when read

III. useful member functions:

• ‘get()‘: extract one character from the stream

• ‘getline()’

· istream::getline() – extract characters until delimiter or specific size

· std::getline() – extract characters from stream into string

• ‘ignore()‘: extract and discard characters from the input stream

• ‘peek()‘: return next character without extracting from the input stream

• ‘unget()‘: return last character back into stream, can be read again

• ‘putback(char c)‘: put character back into the stream, can be read by next call

13.3. Output with ‘ostream’ and ‘ios’: (Learn C++)

ostream is derived from ios, so formatting can be controlled by ios’s options

A. formatter: there are two ways to change formatting options:

1. flag: group of bool variables can be turned on/off

setf(): turn formatting option on i.e. cout.setf(ios::showpos)

unsetf(): turn formatting option off i.e. cout.unsetf(ios::showpos)

2. manipulator: objects placed in the stream affecting the way of output

i.e. cout << hex << 27 << endl → 1B

B. useful formatter:

• ‘boolalpha‘: print boolean “true” or “false”, instead of 0 or 1

• ‘showpos‘: if set, positive number prefixed with ‘+’

• ‘uppercase‘: use upper or lower case letter ↔ ‘nouppercase’

• ‘dec‘, ‘hex‘, ‘oct‘: print value in decimal, hexadecimal and cotal

C. Precision, Notation, Decimal point:

• ‘fixed’: decimal notation for floating-point value

• ‘scientific’: scientific notation for floating-point value

• ‘setprecision(int)’: set # of decimal places or significant digits displayed

• ‘showpoint’: show decimal point and trailing zero(0)s

D. Width, Fill and Aligned:

• ‘setw(int)’: set field-width for input and output operation

• ‘setfill(char)’: set character to fill the blank, default is blank

• ‘left’: left-aligned sign and value

• ‘right’: right-aligned sign and value

• ‘internal’: left-aligned sign and right-aligned value

13.4. Stream class for strings: (Learn C++)

object of this class use string buffer to hold data for processing later i.e. parsing

there are 6 string stream classes, but you may use the stringstream class mainly

because stringstream is derived from iostream it support common operation and

functions i.e. ‘<<‘, ‘>>’, ‘getline()’, ‘ignore()’, ‘clear()’, ‘fill()’

Code Example

13.5. Stream states and input validation: (Learn C++)

I. stream state

is the signal for indicating certain condition occurred in using the stream

four bits consisting of  bitmask to represent stream error state flag, iostate

• goodbit: no error occurred

• badbit: fatal error occurred

• failbit: error(but not fatal) occurred

• eofbit: reached end of file

if any bits are set except a goodbit, then further stream operations are ignored

ios provide functions check whether the state flag set i.e. good(), bad(), fail(), eof()

* see state flag functions part is ios

II. Input Validation

to check whether the input data meet the criterion: mainly string and numeric

C++ not provide high-level one to check validation, but useful primitive functions

so you can build your own validator by composing the primitive blocks

A. String Validation

best way to validate string is checking each characters meet the criterion

cctype provide useful function for character validation i.e. isalpha(), isdigit()

Code Example

B. Numeric Validation

1. via stream operation and stream state flag: Code Example

• if first character in the input stream is not digit, fail flag set occurred

2. via string conversion and exception handeling: Code Example

• see the string conversion function part, in string

13.6. Basic file I/O: (Learn C++)

All of file I/O classes are derived from normal I/O classes, just few things added

There are three basic file I/O classes

• ‘ifstream‘: derived from istream – input

• ‘ofstream‘: derived from ostream – output

• ‘fstream‘: derived from iostream – input/output

can simply instantiate file I/O object with just file name path as a paramter

13.7. Random file I/O: (Learn C++)

I. File Pointer

every file stream class have their own file pointers used to keep track of position in file for read / write operation from / to the file

II. Random File Access

if the file only can be accessed sequentially, it would become very inefficient

A. File pointer:

file pointer make random file access possible

istream::seekg(): set file pointer at the position of next character extracted

ostream::seekp(): set file pointer at the position of next character inserted

istream::tellg(): return absolute position of file pointer on input stream

ostream::tellp(): return absolute position of file pointer on output stream

∗ ‘g’:get – input , ‘p’: put – output

B. std::fstream: read / write

because ftsream is derived from iostream, and iostream is derived from both istream and ostream, it support both read / write operation on file.

however you must call seekg() or seekp() before, if you want switch context from read to write or from write to read. Otherwise something weird will occur


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s