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

Chapt 14. Template

14.1 Function Template (Learn C++)

Write one function, Work with different parameter types


14.2 Function Template Instance: (Learn C++)

function template with actual parameter type is compiled at run time.

14.3 Template Classes: (Learn C++)

template class is useful for containers dealing with various data types

template class is compiled at run time. so if you don’t use it, never compiled


Chapt 15. Exceptions

15.1. Introduction to Exception Handling: (Learn C++)

Exception handling provide more flexible mechanism to decouple error handling from typical control flow of code

15.2. Basic Exception Handling: (Learn C++)

Exception handling in C++ implemented with three parts: throw, try, catch

• throw statement:

act as the signal to indicate that exceptions or errors have occurred

throw keyword + single value of data type(used to identify appropriate handler)

• try block:

act as observer to observe any exceptions or errors occurred in try block

* when throw statement executed, the remaining part of try block must be never reached, and so never executed

• catch block:

act as handler to handle the exceptions or errors with matched signal data type

multiple catch block in sequence possible

∗ if there no appropriate catch handler exist, exception handling delegated to next nearest try-catch block, if no more try-catch block exist the program will fail witch exception errors

15.3. Exceptions, Functions and Stack Unwinding: (Learn C++)

In C++ functions, even if main(), not necessarily handle exceptions thrown by them.

It means, function can delegate the exception handling to the caller of it. When this happen stack(function call stack) unwinding occurred.

If the caller also has no appropriate exception handler, exception recursive delegated to the caller of the caller.

In this way, it can be implemented to handle the exception with different context. i.e. print text error message, display pop up menu, terminate program immediately

15.4. Uncaught exceptions, catch-all handlers: (Learn C++)

• uncaught exception:

If it is happen that exception is not caught by any function, even if by main, the program will be forced to terminate. Then handling the exception is totally dependent on your OS

• catch-all handler: catch(…)

catch-all handler make it possible to catch all exceptions occurred in try block.

To ensure handling the specific exception, it is recommended to put the catch-all handler at last position of try-catch block. * visual studio enforce this constraint

15.5. Exception, Classes and Inheritance: (Learn C++)

• Exception and member functions:

Exception handling, throw-try-catch, can be achieved in member function

* Therefore, errors when occurred in constructing object can be handled by throw-try-catch block. Constructing processed immediately aborted and destructor never executed.

• Exception class:

1. Object of any class type can be thrown as exception parameter

2. Exception class is just a normal class designed specifically to be thrown for dealing with specific context or problem.

* should catch exception class parameter as reference variable for performance

3. std::exception class:

commonly used by C++ standard library classes for exception handling

• Exception Inheritance:

Flow or controlling catch block is sequential.

So, to handle specific derived class, handler for that derived class must be positioned above the base class.

15.6. Exception dangers and Downsides: (Learn C++)

There some issues you should notice before exploiting the exception handling

• Resource Cleaning

if exception occurred before releasing resource i.e. delete pointer, memory issue will happen. So you should implement releasing resource in catch block, or use some functions automatically releasing resource i.e. std::unique_ptr

• Never Throw Exception in Destructor

destructors always called in stack unwinding process. So if you throw the exception in the desturctor, compiler can’t decided whether to continue stack unwinding process or to handle the new exception. The result is to terminate your program immediately

• Exception slow the performance

if function delegate exception handling to caller, then stack unwinding process necessarily need. It will reduce performance of your program. So cautiously exploit exception handling in case of truly exception cases or fatal errors

Chapt 16. The Standard Template Library

16.1. STL: (Learn C++)

The collection of classes providing templated containers, iterator and algorithms

16.2. STL Containers: (Learn C++)

A. Sequence Containers: maintain order of elements

1. array: static array

2. vector: dynamic array

3. list: doubly linked list

4. forward_list: singly linked list

5. dequeue: double ended queue

 B. Associative Containers: automatically sort elements when inserted

1. set: unique element

2. multiset: duplicated element allowed

3. map(associative array): key/value pair; key must be unique

4. multimap(dictionary): duplicated key allowed map

C. Container Adapters: special predefined containers for specific use

1. stack: LIFO

2. queue: FIFO

3. priority_queue: maintain highest priority element on the top

16.3. STL Iterators: (Learn C++)

iterator(≈ pointer) is the ‘object’ can traverse a container class

become powerful when combined with STL’s algorithms and functions of containers

std::iterator: read / write

std::const_iterator: read only

16.4. STL Algorithms: (Learn C++)

provide a number of generic algorithms work with container classes by using iterators

can work with all container classes(including custom) providing iterator interface

A. Appetizers

find(): return iterator of the first element in the range

minmax(): return pir<min, max> in the range

sort(): sort all elements ascending order in the range

reverse(): reverse the order of elements in the range

Chapt 17. std::string

17.1 std::string and std::wstring (Learn C++)

A. Base class: ‘basic_string<>’

1. std::string: used for ‘UTF-8’

2. std::wstring: used for ‘UTF-16’

*There no built-in string for ‘UTF-32’. Should extend form ‘basic_string<>’

B. Not support functionality

1. Tokenization

2. Capitalization

3. Case-insensitive comparison

4. Whitespace trimming

5. Conversion UTF-8 –> UTF-16

*You should implement above functionality yourself

17.2 std::string construction (Learn C++)

There many constructors for string class, but I’ll only cover common ones; see further

A. Constructors

1. string::string() : default empty string

2. string::string(const string& str) : copy constructor

3. string::string(const string& str, size_t pos, size_t len): substring

4. string::string(const string* str) : copy from C-string

5. string::string(const string* str, size_t n) : copy first ‘n’ characters

5. string::string(size_t n, char c) : fill ‘n’ characters

B. Source Code

17.3 std::string length and capacity (Learn C++)

A. std::string length() == std::string size() – further see

1. return # of bytes used for current contents

2. always equal or less than ‘capacity’ of string

B. std::string capacity() – further see

1. return # of bytes allocated to string

2. always equal or grater than ‘length’ of string

3. memory reallocation is comparatively expensive

C. Source Code

17.4 std::string character access and conversion to C-style arrays (Learn C++)

A. char& operator[] (size_t pos) == char& at (size_t pos)

both function returns the character with index ‘pos’

return type is reference;’char &’. so can edit the character

B. const char* c_str()

return C-style character sequence equal to string

should not be deallocated; it is owned by string object

C. Source Code

17.5 std::string assignment and swapping (Learn C++)

A. string assignment

1. assignment operator ‘=

string& operator= (const string& str)

string& operator= (const char* str)

string& operator= (char c)

2. assignment method ‘assign()

string& assign (const string& str)

string& assign (const char * str)

string& assign (const string &str, size_t subpos, size_t sublen)

string& assign (size_t n, char c)

B. swapping

void string::swap (string& str)

void swap (string& str1, string& str2)

C. Source Code

17.6 string appending (Learn C++)

A. appending operator ‘+=

string& operator+= (const string& str)

string& operator+= (const char * s)

string& operator+= (char c)

B. appending method ‘append()

string& append (const string& str)

string& append (const string& str, size_t subpos, size_t sublen)

string& append (const char* s)

string& append (const char* s, size_t n) – not recommend to use

string& append (size_t n, char c)

C. appending method ‘push_back()

void push_back (char c)

D. Source Code

17.7 std::string inserting (Learn C++)

A. inserting method ‘insert()

string& insert (size_t pos, const string& str)

string& insert (size_t pos, const string& str, size_t subpos, size_t sublen)

string& insert (size_t pos, const char* s)

string& insert (size_t pos, const char* s, size_t n)

string& insert (size_t pos, size_t n, char c)

B. Source Code

Unit 1. The Internet and IP

1.0. The Internet and IP

1.1. A day in the list of an application

1.2. The 4 layer Internet model

1.3. The IP service model

1.4. A day in the life of a packet

1.5. The principle of Packet Switching

1.6. The principle of Layering

1.7. The principle of Encapsulation

1.8. The Byte order and Packet formats

1.9. IPv4 addresses and CIDR

1.10. Longest Prefix Match: LPM

1.11. Address Resolution Protocol

1.12. The Internet and IP(recap)

1.13. SIP — Jon Peterson