Reference informa9on Consult reference for complete - - PDF document

reference informa9on
SMART_READER_LITE
LIVE PREVIEW

Reference informa9on Consult reference for complete - - PDF document

2014-10-13 Reference informa9on Consult reference for complete informa9on! UNIX man-pages (available on exam): Lecture 3 man topic man istream


slide-1
SLIDE 1

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! ¡

¡

slide-2
SLIDE 2

2014-­‑10-­‑13 ¡ 2 ¡

Think ¡of ¡speech! ¡

  • A ¡sequence ¡of ¡words. ¡
  • Have ¡a ¡source: ¡mouth ¡(brain?) ¡
  • Have ¡a ¡des9na9on: ¡ear ¡(brain?) ¡
  • You ¡can ¡not ¡choose ¡to ¡hear ¡later ¡words ¡before ¡
  • earlier. ¡
  • You ¡can ¡not ¡choose ¡to ¡hear ¡a ¡word ¡again. ¡
  • It’s ¡a ¡stream! ¡

Hey! ¡What ¡if... ¡

  • I ¡have ¡a ¡different ¡source? ¡iPad, ¡Compact ¡Disc ¡

– Sure, ¡some ¡specific ¡sources ¡have ¡addi-onal ¡ capabili9es, ¡more ¡than ¡the ¡standard ¡stream. ¡

  • I ¡ask ¡the ¡stream ¡to ¡replay? ¡

– NO. ¡Will ¡refuse ¡to ¡replay. ¡Some9mes ¡it ¡can ¡let ¡you ¡ peek ¡on ¡what’s ¡coming, ¡but ¡don’t ¡depend ¡on ¡it. ¡

  • I ¡record ¡the ¡speech? ¡

– Sure, ¡you ¡can ¡record ¡any ¡stream ¡(the ¡sound), ¡but ¡you ¡ can ¡not ¡copy ¡the ¡stream ¡itself ¡(the ¡one ¡who ¡talk)! ¡

C++ ¡streams ¡

  • Variables ¡of ¡composed, ¡object, ¡type ¡
  • One ¡type ¡fits ¡all ¡

– istream ¡(in ¡to ¡program, ¡program ¡is ¡des9na9on) ¡ – ostream ¡(out ¡from ¡program, ¡program ¡is ¡source) ¡

  • Three ¡kinds ¡of ¡specific ¡streams ¡

– General ¡I/O: ¡cin, ¡cout, ¡cerr, ¡clog ¡ – File ¡streams ¡(file ¡on ¡disk ¡act ¡as ¡source ¡or ¡des9na9on) ¡ – S9ng ¡streams ¡(string ¡variable ¡in ¡memory ¡act ¡as ¡source ¡

  • r ¡des9na9on) ¡

File ¡stream ¡input ¡

Must ¡be ¡connected ¡to ¡a ¡file ¡on ¡disk ¡before ¡use. ¡ #include <fstream> ifstream infile; // create stream object infile.open(”data.txt”); // connect stream // object ifstream in(”data.txt”); // create and // connect int a, b; in >> a; // read from ’in’ infile >> b; // what do you get?? in.close(); // disconnect

File ¡stream ¡output ¡

Must ¡be ¡connected ¡to ¡a ¡file ¡on ¡disk ¡before ¡use. ¡ #include <fstream>

  • fstream ofile; // create stream object
  • file.open(”data.txt”); // connect stream

// object

  • fstream out(”data.txt”); // create and

// connect int a{4711}, b{512};

  • ut << a; // write to ’out’
  • file << b; // what is in the file??
  • ut.close(); // disconnect

String ¡stream ¡input ¡

Must ¡be ¡connected ¡to ¡a ¡string ¡variable ¡before ¡use. ¡ #include <sstream> string data{”4711 512”}; istringstream instr; // create stream instr.str(data); // connect stream istringstream in(data); // create, connect int a, b; in >> a; // read from ’in’ instr >> b; // what do you get??

slide-3
SLIDE 3

2014-­‑10-­‑13 ¡ 3 ¡

String ¡stream ¡output ¡

#include <sstream>

  • stringstream outstr; // create stream

int a{4711}, b{512};

  • utstr << a << b;

string str{outstr.str()}; // what is in ’str’?

Stream ¡error ¡sources ¡

  • Every ¡stream ¡will ¡SILENTLY ¡REFUSE ¡further ¡
  • pera9on ¡afer ¡ANY ¡failure: ¡
  • End ¡of ¡file ¡

– A ¡file ¡stream ¡reach ¡end ¡of ¡file ¡ – A ¡string ¡stream ¡reach ¡end ¡of ¡file ¡(string) ¡ – User ¡press ¡Ctrl-­‑D ¡to ¡signal ¡end ¡of ¡input ¡

  • Logic ¡failure ¡

– Conversion ¡from ¡characters ¡to ¡number ¡fail ¡

  • Serious ¡error ¡

– Like ¡hardware ¡failure ¡

Error ¡checking ¡

  • Must ¡be ¡performed ¡just ¡aCer ¡each ¡opera9on ¡
  • Provide ¡possibility ¡to ¡detect ¡error ¡
  • Almost ¡never ¡used ¡explicitly! ¡
  • Four ¡opera9ons ¡available: ¡

bool eof(); // slammed into eof? bool fail(); // conversion failed? bool bad(); // unrecoverable? bool good(); // no error set?

Peculiari9es ¡(that ¡make ¡sense) ¡

  • bad() ¡and ¡good() ¡are ¡not ¡opposites ¡

– A ¡stream ¡may ¡be ¡!good() ¡even ¡if ¡it’s ¡!bad() ¡

  • fail() ¡and ¡good() ¡are ¡not ¡opposites ¡

– A ¡stream ¡may ¡be ¡!good() ¡even ¡if ¡it’s ¡!fail() ¡

  • eof() ¡can ¡be ¡set ¡when ¡fail() ¡is ¡not ¡set ¡

– Input ¡can ¡succeed ¡despite ¡slamming ¡into ¡eof! ¡

Error ¡checking ¡”as ¡usual” ¡

int a, b; cin >> a >> b; if (cin) { // formatted input did not fail } while (cin >> a) { // formatted input did not fail }

Error ¡clearing ¡

  • Every ¡stream ¡will ¡REFUSE ¡further ¡opera9on ¡

afer ¡ANY ¡failure! ¡

  • Errors ¡must ¡be ¡cleared ¡before ¡stream ¡can ¡be ¡
  • perated ¡again! ¡
  • Clearing ¡an ¡error ¡will ¡NOT ¡EVER ¡fix ¡the ¡

problem! ¡ // clear all errorflags void clear();

slide-4
SLIDE 4

2014-­‑10-­‑13 ¡ 4 ¡

Fixing ¡the ¡problem ¡

  • When ¡a ¡stream ¡encounter ¡an ¡error ¡the ¡situa9on ¡or ¡

data ¡that ¡caused ¡the ¡error ¡will ¡remain! ¡

  • Step ¡one: ¡

– detect ¡that ¡you ¡have ¡a ¡problem, ¡just ¡aCer ¡each ¡opera-on ¡ if ( ! (cin >> i) )

  • Step ¡two: ¡

– clear ¡the ¡stream ¡so ¡it ¡will ¡cooperate ¡ cin.clear();

  • Step ¡three: ¡

– remove ¡the ¡data ¡that ¡caused ¡the ¡error! ¡ cin.ignore(1024, ’\n’);

Remove ¡offending ¡data ¡

char c; int max; string s; while ( cin.get(c) && c != ’\n’ ) ; // no operation max = numeric_limits<streamsize>::max(); cin.ignore(max, ’\n’); getline(cin, s, ’\n’); cin >> s;

Fail-­‑safe ¡reading ¡

cout << ”enter number < 10”; cin >> number; if ( !cin.fail() ) if ( number < 10 ) // success else // good read but stupid user else if ( cin.bad() ) // unrecoverable else if ( cin.eof() ) // failed due to end of file else // conversion failed, recover

Hey! ¡What ¡really ¡happens? ¡

int a, b; (cin >> a) >> b; if (cin) { // formatted input did not fail } while (cin >> a) { // formatted input did not fail }

Formahed ¡I/O ¡

  • Applies ¡conversion ¡from ¡stream ¡byte ¡sequence ¡to ¡

requested ¡data ¡type, ¡or ¡from ¡given ¡data ¡type ¡to ¡ stream ¡byte ¡sequence. ¡

  • Formahed ¡input ¡may ¡fail! ¡
  • Returns ¡reference ¡(lvalue!) ¡to ¡stream ¡you ¡used! ¡

// formatted input istream& operator>>(...) // formatted output

  • stream& operator<<(...)

Unformahed ¡input ¡

  • No ¡conversion ¡take ¡place. ¡
  • Does ¡not ¡fail ¡(unless ¡you ¡hit ¡end ¡of ¡file ¡or ¡failed ¡

to ¡clear ¡previous ¡errors!) ¡ istream& get(char& c); istream& ignore(streamsize, int); istream& get(char& c); istream& read(char*, streamsize); istream& getline(istream&, string&, int);

slide-5
SLIDE 5

2014-­‑10-­‑13 ¡ 5 ¡

Unformahed ¡output ¡

  • No ¡conversion ¡take ¡place. ¡
  • Does ¡not ¡fail ¡(unless ¡you ¡hit ¡end ¡of ¡file ¡or ¡fail ¡

to ¡clear ¡previous ¡errors!) ¡

  • stream& put(char c);
  • stream& flush();
  • stream& write(const char* s,

streamsize n);

Seeking ¡in ¡filestreams ¡

  • Filestreams ¡can ¡perform ¡next ¡opera9on ¡at ¡any ¡posi9on ¡in ¡

the ¡file: ¡ istream& tellg(); istream& seekg(streampos pos, seekdir dir);

  • stream& tellp();
  • stream& seekp(streampos pos,

seekdir dir);

  • Three ¡seek ¡reference ¡posi9ons: ¡

ios::beg // beginning of file ios::cur // current position ios::end // end of file

Modes ¡for ¡filestreams ¡

  • Files ¡can ¡be ¡opened ¡in ¡several ¡modes. ¡
  • Files ¡should ¡be ¡closed ¡as ¡soon ¡as ¡possible. ¡

void open(const string& name,

  • penmode mode);

void close();

  • Possible ¡openmodes: ¡

ios::app ios::ate ios::trunc ios::out ios::in ios::binary

Manipulators ¡

  • Can ¡affect ¡how ¡formahed ¡I/O ¡conversion ¡behave. ¡

#include <iomanip> setprecision(int) fixed, scientific setfill(char), setw(int) left, right

  • ct, dec, hex, boolalpha

skipws, flush, endl

Stream ¡references ¡

  • Streams ¡can ¡be ¡sent ¡to ¡func9ons, ¡and ¡

returned ¡from ¡func9ons ¡as ¡references! ¡

  • It ¡must ¡be ¡reference! ¡You ¡can ¡not ¡copy! ¡
  • Use ¡the ¡generic ¡istream&, ¡ostream& ¡types ¡

– An ¡ifstream ¡is ¡an ¡istream ¡ – An ¡istringstream ¡is ¡also ¡an ¡istream ¡ – cin ¡is ¡an ¡istream ¡

Print ¡table ¡to ¡any ¡stream! ¡

  • stream& print_table(ostream& os)

{ for (int i{0}; i < 10; i = i + 1) {

  • s << setw(4) << i << endl;

} return os; }

slide-6
SLIDE 6

2014-­‑10-­‑13 ¡ 6 ¡

Using ¡the ¡print ¡func9on! ¡

int main() {

  • fstream file(”table.txt”);

if ( ! file ) throw ios::failure(”open failed!”); print_table(file); file.close(); print_table(cout) << ”.” << endl; return 0; }

Read ¡to ¡end ¡of ¡file ¡(1 ¡of ¡3) ¡

  • This ¡is ¡the ¡most ¡common ¡pilall. ¡WRONG! ¡

int value; while ( !cin.eof() ) { cin >> value; cout << value; }

Read ¡to ¡end ¡of ¡file ¡(2 ¡of ¡3) ¡

  • This ¡is ¡beher ¡but ¡STILL ¡WRONG! ¡

int value; cin >> value; while ( ! cin.eof() ) { cout << value; cin >> value; }

Read ¡to ¡end ¡of ¡file ¡(3 ¡of ¡3) ¡

  • This ¡is ¡the ¡simplest ¡and ¡best ¡solu9on ¡

int value; while (cin >> value) { cout << value; }

Read ¡line ¡by ¡line ¡

// read until failure (any reason) while ( getline(cin, line) ) { cout << line << endl; } // what happens here? while ( getline(cin >> number, line) ) { cout << line << ’:’ << number << endl; }

Interpret ¡line ¡by ¡line ¡

// Read line first, then interpret it! while ( getline(cin, line) ) { istringstream iss(line); int count{0}, number; while (iss >> number) { count = count + 1; } cout << ”Line had ” << count << ” numbers!” << endl; }

slide-7
SLIDE 7

2014-­‑10-­‑13 ¡ 7 ¡

Type ¡conversion ¡

  • If ¡you ¡can ¡read ¡a ¡type ¡from ¡cin ¡you ¡can ¡also ¡

convert ¡a ¡string ¡to ¡that ¡type! ¡

  • If ¡you ¡can ¡write ¡a ¡type ¡to ¡cout ¡you ¡can ¡also ¡

convert ¡that ¡type ¡to ¡a ¡string! ¡

  • Just ¡use ¡a ¡stringstream! ¡

istringstream iss(str_rep); double dbl_rep; iss >> dbl_rep;

  • Note: ¡This ¡is ¡likely ¡to ¡introduce ¡rounding ¡errors!! ¡

Handling ¡files ¡

string filename; cout << ”Enter filename: ”; cin >> filename; ifstream fileobject(filename); if ( ! fileobject ) { cerr << ”Could not open ’” << filename << ”’.” << endl; throw ios::failure(”File open failed.”); } // Use your open fileobject here! fileobject.close();

Binary ¡files ¡

  • Some ¡people ¡store ¡data ¡to ¡files ¡without ¡

conver9ng ¡it ¡to ¡strings ¡first: ¡

– saves ¡storage ¡space ¡ – no ¡conversion ¡errors ¡due ¡to ¡rounding ¡ – efficient ¡read ¡and ¡write ¡(no ¡conversion, ¡right?) ¡

  • But: ¡

– problema9c ¡to ¡move ¡files ¡between ¡architectures ¡ – not ¡human ¡readable ¡files ¡

Byte ¡order ¡(endianness) ¡

  • Endian-­‑mess ¡really! ¡

– lihle ¡endian: ¡x86, ¡alpha, ¡avr ¡ – big ¡endian: ¡motorola, ¡sparc, ¡ibm ¡

  • Why ¡all ¡the ¡fuzz? ¡

– consider ¡a ¡4 ¡byte ¡integer ¡type ¡placed ¡at ¡address ¡X ¡ – do ¡you ¡place ¡the ¡least ¡significant ¡bits ¡in ¡X+0? ¡(lihle) ¡ – or ¡do ¡you ¡place ¡the ¡least ¡significant ¡bits ¡in ¡X+3? ¡(big) ¡ – answer: ¡people ¡do ¡both! ¡ – what ¡happen ¡when ¡you ¡write ¡one ¡way ¡and ¡read ¡the ¡

  • ther ¡way? ¡yes, ¡you ¡guessed ¡it! ¡you ¡get ¡weird ¡values! ¡

Binary ¡file ¡example ¡

// Method only for fundamental types! Not string! double pi{3.14159265359}; char* adr_to_pi{nullptr}; adr_to_pi = reinterpret_cast<char*>(&pi);

  • fstream ofs(”pi.bin”, ios::binary);
  • fs.write(adr_to_pi, sizeof(pi));

double in; char* adr_to_in{nullptr}; adr_to_in = reinterpret_cast<char*>(&in); ifstream ifs(”pi.bin”, ios::binary); ifs.read(adr_to_in, sizeof(in));

More ¡on ¡typecas9ng ¡

to_type(from_type)

– Usually ¡simplest. ¡

static_cast<to_type>(from)

– For ¡pointer ¡cast ¡between ¡related ¡types. ¡

reinterpret_cast<to_type>(from)

– For ¡pointer ¡cast ¡between ¡unrelated ¡types ¡(DANGER!). ¡

dynamic_cast<to_type>(from)

– With ¡run-­‑9me ¡type-­‑check. ¡Introduced ¡later ¡in ¡course. ¡

const_cast<to_type>(from)

– DO ¡NOT ¡USE. ¡Violates ¡purpose ¡of ¡const. ¡ – You ¡will ¡not ¡encounter ¡any ¡excep9ons ¡in ¡the ¡course. ¡

slide-8
SLIDE 8

2014-­‑10-­‑13 ¡ 8 ¡

To ¡be ¡con9nued. ¡

This ¡page ¡is ¡not ¡lef ¡blank. ¡Inten9onally. ¡