40
Namespaces, Namespaces, I/O streams I/O streams

Namespaces, I/O streams. Namespaces Namespace – what’s this? Namespace – what’s this?namespace When do we need the namespace? When do we need the namespace?

  • View
    290

  • Download
    1

Embed Size (px)

Citation preview

Namespaces, Namespaces, I/O streamsI/O streams

NamespacesNamespaces

Namespace – what’s this?Namespace – what’s this?

namespacenamespace

When do we need the namespace?When do we need the namespace?

Namespaces – usingNamespaces – using

namespace namespace minemine{{

void printf(int);void printf(int);class class filefile;;void fprintf(const void fprintf(const file file &, int);&, int);

}}

minemine::printf(44);::printf(44);minemine::::filefile infileinfile;;fprintf(fprintf(infileinfile, 31415323);, 31415323); // if at least one function argument comes from// if at least one function argument comes from

// the „mine” namespace, then the function // the „mine” namespace, then the function // fprintf() is looked for in this namespace first// fprintf() is looked for in this namespace first// (Koenig search rule)// (Koenig search rule)

Namespaces – usingNamespaces – using Namespaces may be extended/joinedNamespaces may be extended/joined

in a single source filein a single source file in many filesin many files

Any given name (or all the names) may be moved from Any given name (or all the names) may be moved from namespace scope to the global (or local) scopenamespace scope to the global (or local) scope using mine::file; using mine::file; using namespace mine;using namespace mine;

Avoid using „using” in the header files!Avoid using „using” in the header files! why?why? use the scope operator instead.use the scope operator instead.

Namespace stdNamespace std

The C++ standard library is defined in the std The C++ standard library is defined in the std namespace.namespace. stream classesstream classes string classesstring classes STLSTL

headers „with headers „with ..h” and „without h” and „without ..h”h” interesting fact: „*interesting fact: „*..hpp” and „*hpp” and „*..hxx” are considered hxx” are considered

obsolete and non-standardobsolete and non-standard

Standard C++ I/O streamsStandard C++ I/O streams

IOStream library (iostream)IOStream library (iostream) it’s the oldest part of the standard libraryit’s the oldest part of the standard library developed by AT&Tdeveloped by AT&T

support for internationalizationsupport for internationalization string types supported by librarystring types supported by library

char * (compatibility with earlier routines)char * (compatibility with earlier routines) stringstring

iostream is a library of templates,iostream is a library of templates, iostream uses exception mechanismiostream uses exception mechanism

IOStream library – basicsIOStream library – basics

classesclasses

input stream input stream istreamistream (from template: (from template: basic_istream<char>) basic_istream<char>)

output stream output stream ostreamostream (from template: (from template: basic_ostream<char>)basic_ostream<char>)

IOStream library – basicsIOStream library – basics

objects (header file: <iostream>)objects (header file: <iostream>)

istream istream cincin; ; //stdin , buffered//stdin , buffered

ostream ostream coutcout; ; //stdout, buffered//stdout, buffered ostream ostream cerrcerr; ; //stderr, //stderr, not bufferednot buffered

//by default outputs to console//by default outputs to console ostream ostream clogclog; ; //no C equivalent, buffered//no C equivalent, buffered

//by default outputs to console//by default outputs to console

IOStream library – basicsIOStream library – basics operators << and >>operators << and >>

overloaded for fundamental types, including char *, void *, bool,overloaded for fundamental types, including char *, void *, bool, to be overloaded for classes requiring stream i/oto be overloaded for classes requiring stream i/o

istream is; istream is; ostream os;ostream os;

int i; double d;int i; double d;

os<<i; os<<i; is>>i;is>>i;os<<d;os<<d; is>>d;is>>d;os<<i<<d;os<<i<<d; is>>i>>d;is>>i>>d;cout<<i<<d;cout<<i<<d; cin>>i>>d;cin>>i>>d;cout<< cout<< ""\n\ni is i is " " << i << << i << "" and d is and d is "" << d << << d << " " \n\n"";;

IOStream library – basicsIOStream library – basics Manipulators Manipulators

this are this are objectsobjects used to modify default behaviour of a stream (e.g. used to modify default behaviour of a stream (e.g. formatting), output „end of line” etc.formatting), output „end of line” etc.

programmer may define his own operatorsprogrammer may define his own operators

endl endl //outputs end of line and flushes the stream buffer//outputs end of line and flushes the stream buffer

cout<< cout<< ""\n\ni is i is " " << i << << i << "" and d is and d is "" << d << << d << endlendl;;

endsends // // ""\0\0"";;wsws // for istream stream read (and skip) white spaces// for istream stream read (and skip) white spacesflushflushdec, hex, oct dec, hex, oct

IOStream library – detailsIOStream library – details

ios_baseios_base

basic_streambuf<> basic_streambuf<>

basic_ios<>basic_ios<> virtualvirtual

basic_istream<>basic_istream<> basic_ostream<> basic_ostream<>

basic_iostream<>basic_iostream<>

IOStream library – detailsIOStream library – details

ios_baseios_base

common interface for stream classes common interface for stream classes independent on the class/type of the stream independent on the class/type of the stream elementselements current condition of the streamcurrent condition of the stream formatting of the data being processedformatting of the data being processed

IOStream library – detailsIOStream library – details

basic_ios<>basic_ios<>

common interface for stream classes in extent common interface for stream classes in extent dependent on the class/type of the stream dependent on the class/type of the stream elementselements definition of the stream buffer (class derived from definition of the stream buffer (class derived from

template basic_streambuf<> for specific class/type template basic_streambuf<> for specific class/type of the stream element, definitions of methods of the stream element, definitions of methods actually reading/writting data)actually reading/writting data)

IOStream library – detailsIOStream library – details

basic_istream<>basic_istream<>basic_ostream<>basic_ostream<>

templates for classes of read-only/write-only templates for classes of read-only/write-only streamsstreams they inherit they inherit virtuallyvirtually template basic_ios<> template basic_ios<> for the for the charchar template argument they’re derived template argument they’re derived

from istream i ostream respectivelyfrom istream i ostream respectively headers: <istream> and <ostream>headers: <istream> and <ostream>

IOStream library – detailsIOStream library – details

basic_iostream<>basic_iostream<>

templates of stream classes capable of reading templates of stream classes capable of reading andand writting writting header <istream>header <istream>

IOStream library – detailsIOStream library – details

result of stream operationsresult of stream operations status of the stream (within scope of ios_base, status of the stream (within scope of ios_base,

constants of type iostate)constants of type iostate) goodbitgoodbit // everything ok// everything ok // bits described below are zeroes// bits described below are zeroes eofbiteofbit // end of file reached// end of file reached failbitfailbit // last operation failed// last operation failed // following operations will fail// following operations will fail // until failbit gets set to 0// until failbit gets set to 0 badbitbadbit // failure; stream destroyed// failure; stream destroyed

IOStream library – detailsIOStream library – details

result of stream operations - methodsresult of stream operations - methods bool good()bool good() // everything ok// everything ok bool eof() bool eof() // end of file reached// end of file reached bool fail() bool fail() // last operation failed// last operation failed bool bad() bool bad() // failure; stream destroyed// failure; stream destroyed rdstate()rdstate() // read the stream state// read the stream state clear()clear() // set the state to goodbit// set the state to goodbit clear(state)clear(state) // set state to state// set state to state setstate(state)setstate(state) //equivalent of//equivalent of

// clear(rdstate() // clear(rdstate() || state) state)

IOStream library – detailsIOStream library – details

result of stream operations – conversion operatorsresult of stream operations – conversion operators operator void* ()operator void* () // equivalent of !fail()// equivalent of !fail()

if (cin>>x) if (cin>>x) // or: while(cin>>x)// or: while(cin>>x){ { // x read without an error// x read without an error}}

operator ! () operator ! () // equivalent of fail()// equivalent of fail()

if ( !!(cin>>x)) if ( !!(cin>>x)) // or: while( !!(cin>>x))// or: while( !!(cin>>x)){ { // x read without an error// x read without an error}}

IOStream library – detailsIOStream library – details result of stream operations – exceptionsresult of stream operations – exceptions

to define when to throw exceptions (method of stream to define when to throw exceptions (method of stream class):class):

exceptions(flags)exceptions(flags)

to check what may cause throwing exceptions (method of to check what may cause throwing exceptions (method of stream class):stream class):

exceptions() exceptions()

if it returns goodbit, then exceptions are never thrownif it returns goodbit, then exceptions are never thrown

IOStream library – detailsIOStream library – details

i/o – formatted and unformattedi/o – formatted and unformatted

operators << and >> operators << and >> by defaultby default do formatted i/o do formatted i/o (specific precision, skipping white spaces etc.)(specific precision, skipping white spaces etc.)

methods get*/put*/read*/write* etc. are for methods get*/put*/read*/write* etc. are for unformatted i/o onlyunformatted i/o only

IOStream library – detailsIOStream library – details

formatted i/oformatted i/o methods for format flags (ios::fmtflags)methods for format flags (ios::fmtflags)

setf(flags);setf(flags); // set flags// set flags setiosflags(flags);setiosflags(flags); // equivalent to setf(flags);// equivalent to setf(flags); setf(flags, mask);setf(flags, mask); // set flags within the mask group only// set flags within the mask group only resetiosflags(mask);resetiosflags(mask); // equivalent to setiosflags(0, mask);// equivalent to setiosflags(0, mask); unsetf(flags);unsetf(flags); // clear flags// clear flags flags();flags(); // retrn flags currently set// retrn flags currently set flags(flags);flags(flags); // set flags, clear all the remaining// set flags, clear all the remaining copyfmt(stream)copyfmt(stream) // copy flags from stream// copy flags from stream

IOStream library – detailsIOStream library – details formatted i/o formatted i/o

flags and masks flags and masks boolalphaboolalpha // flag: type bool numeric (0/1) or descriptive// flag: type bool numeric (0/1) or descriptive // true/false// true/false

// there are also manipulators: boolalpha and noboolalpha// there are also manipulators: boolalpha and noboolalpha

adjustfieldadjustfield // mask: alignment (left, right, internal)// mask: alignment (left, right, internal) leftleft // flag: align to left// flag: align to left rightright // flag: align to right// flag: align to right internalinternal // flag: for digits align sign to left// flag: for digits align sign to left // remaining characters to right// remaining characters to right

// there are also manipulators: left, right and internal// there are also manipulators: left, right and internal

IOStream library – detailsIOStream library – details formatted i/o formatted i/o

flags and masks flags and masks showposshowpos // output „+” for positive numbers// output „+” for positive numbers

// there are also manipulators: showpos and noshowpos // there are also manipulators: showpos and noshowpos

uppercaseuppercase // print (upper case) hexadecimal digits // print (upper case) hexadecimal digits // there are also manipulators: uppercase and nouppercase // there are also manipulators: uppercase and nouppercase

basefieldbasefield // mask: for bases of numerical system (see // mask: for bases of numerical system (see below)below)

dec, hex octdec, hex oct // flags for different numerical systems // flags for different numerical systems (empty)(empty) // flag: output as dec, input according to// flag: output as dec, input according to // actual prefix 0x – hex, 0 – oct, else: // actual prefix 0x – hex, 0 – oct, else:

decdec// there are also manipulators: dec hex and oct // there are also manipulators: dec hex and oct

IOStream library – detailsIOStream library – details formatted i/o formatted i/o

flags and masks flags and masks showbaseshowbase // precede numbers with prefix of numerical system// precede numbers with prefix of numerical system

// there are also manipulators: showbase // there are also manipulators: showbase and and noshowbasenoshowbase

floatfieldfloatfield // mask: format of the floating point// mask: format of the floating point fixedfixed // decimal fraction (eg. 3.14159265323)// decimal fraction (eg. 3.14159265323) scientificscientific // use exponent (eg. 3.14e+0)// use exponent (eg. 3.14e+0) (empty)(empty) // pick best one depending on value being oputput// pick best one depending on value being oputput

// there are also manipulators: fixed // there are also manipulators: fixed andand scientific scientific

showpointshowpoint // always output the dot (3// always output the dot (3..1415)1415)

// for the floating point // for the floating point

// there are also manipulators: showpoint // there are also manipulators: showpoint andand noshowpoint noshowpoint

IOStream library – detailsIOStream library – details

formatted i/oformatted i/o precision()precision() // return the precision // return the precision

// for the floating point, // for the floating point,

// by default 6 digits after dot// by default 6 digits after dot precision(p)precision(p) // return the precision // return the precision

// for the floating point // for the floating point

// there is also manipulator: // there is also manipulator: setprecision(w)setprecision(w)

IOStream library – detailsIOStream library – details

formatted i/o formatted i/o flagsflags

skipwsskipws // skip white spaces// skip white spaces// there are also manipulators: skipws and noskipws// there are also manipulators: skipws and noskipws

unitbufunitbuf // flush the output buffer // flush the output buffer // after each <<// after each <<

// there are also manipulators: unitbuf and nounitbuf// there are also manipulators: unitbuf and nounitbuf

IOStream library – detailsIOStream library – details

formatted i/oformatted i/o width()width() // return width of the filed (number of characters)// return width of the filed (number of characters) // interpreted as: not less than// interpreted as: not less than width(w)width(w) // set the width of the filed (number of characters)// set the width of the filed (number of characters) // interpreted as: not less than// interpreted as: not less than

// there is also manipulator: setw(w)// there is also manipulator: setw(w)

char buf[80];char buf[80];cin >> setw(sizeof(buffer)) >> buffer;cin >> setw(sizeof(buffer)) >> buffer;

fill() fill() // return character that is used for filling the field// return character that is used for filling the field fill(c) fill(c) // set this character// set this character

// there is also manipulator: setfill(c)// there is also manipulator: setfill(c)

IOStream library – detailsIOStream library – details

formatted i/oformatted i/o methods for internationalization, different methods for internationalization, different

character sets, etc.character sets, etc. described in detail in the library reference ;-)described in detail in the library reference ;-)

IOStream library – detailsIOStream library – details

unformatted i/ounformatted i/o method getmethod get

int get();int get(); // read one character, or EOF// read one character, or EOF // equivalent to getchar()/getc()// equivalent to getchar()/getc()

istream& get(char &c);istream& get(char &c); // no EOF, instead test the stream state// no EOF, instead test the stream state istream& get(char *pc, streamsize cnt)istream& get(char *pc, streamsize cnt) istream& get(char *pc, streamsize cnt, char delim)istream& get(char *pc, streamsize cnt, char delim) // read to pc buffer, stop after having read// read to pc buffer, stop after having read // cnt-1 characters, or after (just before) the delim character// cnt-1 characters, or after (just before) the delim character // do not input delim, append ‘\0’// do not input delim, append ‘\0’ istream& ignore(streamsize cnt, char delim) istream& ignore(streamsize cnt, char delim) // couple variants, read, but do not store// couple variants, read, but do not store

IOStream library – detailsIOStream library – details

unformatted i/ounformatted i/o method getlinemethod getline

istream& getline(char *pc, streamsize cnt)istream& getline(char *pc, streamsize cnt) istream& getline(char *pc, streamsize cnt, char delim)istream& getline(char *pc, streamsize cnt, char delim)

// read to pc buffer, stop after having read// read to pc buffer, stop after having read

// cnt-1 characters, or after (just before) the delim // cnt-1 characters, or after (just before) the delim

// or after reading end of line// or after reading end of line

// delim // delim isis being read from the stream being read from the stream

// if number of read characters is less than cnt // if number of read characters is less than cnt

// then set failbit state// then set failbit state

IOStream library – detailsIOStream library – details

unformatted i/ounformatted i/o methods read and readsome – some aspectsmethods read and readsome – some aspects

istream& read(char *pc, streamsize cnt)istream& read(char *pc, streamsize cnt) // read cnt characters// read cnt characters

streamsize readsome(char *pc, streamsize cnt)streamsize readsome(char *pc, streamsize cnt) // return number of characters read,// return number of characters read, // read no more than cnt-1 characters// read no more than cnt-1 characters // // input only the characters, that already areinput only the characters, that already are

// // in the input buffer in the input buffer (not destructive)(not destructive)

IOStream library – detailsIOStream library – details unformatted i/ounformatted i/o

int peek(char *pc, streamsize cnt)int peek(char *pc, streamsize cnt) // read next character, leave it in the buffer// read next character, leave it in the buffer

istream& unget()istream& unget() // return to the stream one most recently read character// return to the stream one most recently read character // depending on the implementation, you may call it// depending on the implementation, you may call it

// 1 or more times in a row// 1 or more times in a row// if it fails than set badbit// if it fails than set badbit

istream& putback(char c)istream& putback(char c) // as above, but if c is not the most recently read character // as above, but if c is not the most recently read character

// then set badbit// then set badbit

IOStream library – detailsIOStream library – details

unformatted i/ounformatted i/o

ostream& put(char c)ostream& put(char c) // output c to the stream// output c to the stream

ostream& write(const char *pc, streamsize cnt)ostream& write(const char *pc, streamsize cnt) // output cnt characters from pc to the stream// output cnt characters from pc to the stream // do not append the \0// do not append the \0

ostream& flush()ostream& flush()

IOStream library – basicsIOStream library – basics

File stream classesFile stream classes input stream input stream ifstreamifstream (derived from template: (derived from template:

basic_ifstream<char> /derived from basic_ifstream<char> /derived from basic_istream<char> /) basic_istream<char> /)

output stream output stream ofstreamofstream (derived from template: (derived from template: basic_ofstream<char> / derived from basic_ofstream<char> / derived from basic_ostream<char> /)basic_ostream<char> /)

i/o stream i/o stream fstreamfstream (derived from template: (derived from template: basic_fstream<char> / derived from basic_fstream<char> / derived from basic_iostream<char> /)basic_iostream<char> /)

IOStream library – basicsIOStream library – basics

int i;int i;

ifstream infile(„file.txt”);ifstream infile(„file.txt”);

if (! infile)if (! infile)

cout<<„file not opened”;cout<<„file not opened”;

elseelse

infile >>i;infile >>i;

IOStream library – basicsIOStream library – basics

Flags for file streams (from the scope std::ios)Flags for file streams (from the scope std::ios) constructor arguments: fstream(name, flags=def)constructor arguments: fstream(name, flags=def)

inin // flag : input stream, default for ifstream// flag : input stream, default for ifstream outout // flag : output stream, default for ofstream// flag : output stream, default for ofstream appapp // flag : for input stream, set the position to end of file// flag : for input stream, set the position to end of file ateate // flag : set the position to end of file// flag : set the position to end of file trunctrunc // flag : remove the file contents (if not already // flag : remove the file contents (if not already

empty)empty) binarybinary // flag : binary mode (do not interpret CR LF)// flag : binary mode (do not interpret CR LF)

ifstream ibin(„data.bin”, std::ios::in ifstream ibin(„data.bin”, std::ios::in || std::ios::binary); std::ios::binary);

IOStream library – basicsIOStream library – basics

Methods for file streams Methods for file streams openopen // ( file_name [, flags] )// ( file_name [, flags] ) closeclose // ()// () is_openis_open // is the file opened?// is the file opened? tellg/tellptellg/tellp // get actual reading/writting(p) position (offset)// get actual reading/writting(p) position (offset) seekg/seekpseekg/seekp // seek for reading/writting // seek for reading/writting // overloaded variants: relative/absolute // overloaded variants: relative/absolute

positionposition

ifstream ibin(„data.bin”, std::ios::in ifstream ibin(„data.bin”, std::ios::in || std::ios::binary); std::ios::binary);

IOStream library – detailsIOStream library – details

Details on file stream classesDetails on file stream classes described in detail in the library reference ;-) described in detail in the library reference ;-)

IOStream library – basicsIOStream library – basics

Classes for memory streams (string streams)Classes for memory streams (string streams) input stream input stream istringstreamistringstream (derived from template: (derived from template:

basic_istringstream<char> /derived from basic_istringstream<char> /derived from basic_istream<char> /) basic_istream<char> /)

output stream output stream ostringstreamostringstream (derived from (derived from template: basic_ostringstream<char> / derived template: basic_ostringstream<char> / derived from basic_ostream<char> /)from basic_ostream<char> /)

i/o stream i/o stream stringstreamstringstream (derived from template: (derived from template: basic_stringstream<char> / derived from basic_stringstream<char> / derived from basic_iostream<char> /)basic_iostream<char> /)

IOStream library – detailsIOStream library – details

Details on memory stream classesDetails on memory stream classes described in detail in the library reference ;-)described in detail in the library reference ;-)