about
10/27/2022
C++ Story LibraryStreams
Chapter #10 - C++ Stream Libraries
stream types and example code
10.0 Prologue
10.1 Streams
10.2 Streams Formatting Code Examples
-
right, left, and internal adjust in a specified field width:
std::cout.setf(ios::left, ios::adjustfield); -
scientific, fixed, and automatic for floating point numbers:
std::cout.setf(ios::scientific, ios::floatfield); -
dec, oct, and hex for number formatting:
std::cout.setf(ios::hex, ios::basefield);
Table 1. - Partial list of io manipulators
- full listmanipulator | function |
---|---|
<ios> header included in <iostream> header | |
boolalpha, noboolalpha | set text or numeric representations, respectively |
showpoint, noshowpoint | decimal point is always included in floating-point representation |
skipws, noskipws | leading whitespace is skipped on input |
internal, left, right | placement of fill characters |
dec, oct, hex | sets base used for integer I/O |
fixed, scientific, hexfloat, defaultfloat | sets formatting used for floating-point I/O |
<iostream> | |
ends | emits trailing '\0' to terminate string |
flush | flushes output stream |
endl | emits '\n' and flushes output stream |
<iomanip> | |
resetiosflags | clears specified ios_base flags |
setiosflags | sets specified ios_base flags |
setfill | changes fill character which is ' ' by default |
setprecision | specifies number of digits after the point (not precision of output) |
setw | changes width of the next input or output field |
get-time | parses date/time value of specified format |
put-time | formats and outputs a date/time value using specified format |
quoted | inserts and extracts quoted strings with embedded spaces |
Example: std::iostream formats
10.3 File Streams Code Examples
std::ifstream in(filename, ios::in); std::ifstream in; in.open(filename, ios::in); in.close();
- The file name may be incorrect or the file may not exist.
- Other code may have that file opened.
- The user may not have permissions to open the file.
-
good state, tested with the function
bool good() . When good is true the stream operates normally. -
bad state, tested with
bool bad() . Streams in a bad state are fully functional, but will not respond to any commands until the stream error is cleared withvoid clear() . A state can go bad when it attempts to read an end of file integer,eof . To restore normal operation, clear the error and back up at least one character by callingstrm.seek(-1); -
fail state, tested with
bool fail() . Streams in a fail state have been corrupted. The only thing you can do with a failed stream is to destroy it or re-initialize with anopen(filename, ios attributes); .
if(!out.good()) { /* do some clean up and return */ }
Example: std::fstreams I/O
10.4 Filebuf I/O Code Examples
Example: std::Filebuf I/O
10.5 Read-Write Code Examples
Read/Write Streams
10.6 String Streams Code Examples
std::cout << d;
Example: std::stringstreams
10.7 Epilogue
Commentary to be added later