2014-‑10-‑13 ¡ 1 ¡
Lecture ¡3 ¡
Stream ¡I/O ¡
Reference ¡informa9on ¡
- Consult ¡reference ¡for ¡complete ¡informa9on! ¡
- UNIX ¡man-‑pages ¡(available ¡on ¡exam): ¡
man ¡topic ¡ man ¡istream ¡ man ¡ostream ¡ ios, ¡basic_string, ¡stringstream, ¡ctype, ¡numeric_limits ¡
- Online ¡(not ¡available ¡on ¡exam): ¡
www.cplusplus.com/reference/ ¡
File ¡separa9on ¡
- Related ¡(cohesive) ¡func9ons ¡can ¡be ¡gathered ¡in ¡one ¡file ¡to ¡form ¡a ¡
- package. ¡
- A ¡package ¡can ¡be ¡compiled ¡separately, ¡and ¡do ¡not ¡need ¡
recompila9on ¡unless ¡you ¡change ¡a ¡package ¡source ¡file. ¡ ¡
- Public ¡declara9ons ¡are ¡place ¡in ¡a ¡header ¡file ¡*.h ¡
- Defini9ons ¡are ¡placed ¡in ¡a ¡implementa9on ¡file ¡*.cc ¡
- Header ¡and ¡implementa9on ¡files ¡should ¡have ¡the ¡same ¡name, ¡
except ¡for ¡the ¡extension ¡
- Header ¡file ¡must ¡have ¡a ¡preprocessor ¡guard ¡to ¡protect ¡from ¡
mul9ple ¡inclusion ¡ #ifndef _FILE_NAME_H_ #define _FILE_NAME_H_ // public declarations #endif
Genera9ng ¡errors ¡
- Your ¡goal ¡should ¡be ¡to ¡no-ce ¡the ¡program ¡user ¡in ¡a ¡clear ¡
and ¡understandable ¡way ¡and ¡then ¡recover. ¡
- We ¡will ¡cover ¡the ¡recover ¡part ¡later ¡in ¡the ¡course. ¡
- C ¡ways ¡
– Message ¡in ¡program ¡or ¡system ¡log ¡(good) ¡ – Message ¡to ¡standard ¡error ¡(poor) ¡ – Message ¡to ¡standard ¡output ¡(bad) ¡ – Exit ¡program ¡(bad) ¡ – Return ¡error ¡code ¡from ¡func9on ¡(bad) ¡
- C++ ¡ways ¡
– Throw ¡anonymous ¡error ¡(bad) ¡ – Throw ¡specific ¡error ¡(good) ¡
Generate ¡error ¡the ¡C++ ¡way ¡
#include <exception> string msg = “error message” throw invalid_argument(msg); throw logic_error(“bad bool”); throw domain_error(“bad luck”); #include <iostream> throw ios::failure(“bad file”);
Stream ¡concept ¡
- An ¡ordered ¡stream ¡of ¡bytes ¡
- One ¡source ¡generates ¡bytes ¡
- One ¡des9na9on ¡consumes ¡bytes ¡
- Not ¡possible ¡to ¡break ¡the ¡given ¡order ¡
- Des9na9on ¡can ¡not ¡receive ¡again! ¡
- Blind: ¡can ¡not ¡see ¡future! ¡