The C++ Input/Output Class Hierarchy

Size: px
Start display at page:

Download "The C++ Input/Output Class Hierarchy"

Transcription

1 C++ Programming: The C++ Input/Output Class Hierarchy 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering

2 Contents Basics on C++ I/O The I/O class hierarchy The common base I/O classes High-level I/O classes Manipulators 2

3 Basics on C++ I/O C++ I/O facility is not a part of the language Instead, it is furnished through a class library, which consists of a complex class hierarchy Why we examine such class hierarchy in detail The hierarchy illustrates the power available by combining polymorphism and multiple inheritance The hierarchy provides an excellent example of the use of templates By understanding the details of the hierarchy, a programmer can extend the existing I/O classes 3

4 Basics on C++ I/O (cont.) Stream I/O Input to a program is treated as a stream of consecutive bytes from a keyboard, a disk file, or some other sources Output from a program is also treated as a stream of consecutive bytes to a video display, a disk file, or some other destinations Stream Input Plan 9 From Outer Space Plan 9 From Outer Space Plan 9 From Outer Space Stream output Input 4

5 The Stream I/O Class Hierarchy A clean design can be achieved by having common base classes for derived high-level I/O classes The common base I/O classes ios_base: provides a description of the stream without regard to the character set involved Format attributes of the stream (e.g., output justifications) Status of operations on the stream (e.g., whether EOF is encountered) basic_ios: provides a description of the stream with regard to the character set involved ios_base basic_ios Each class is a template with class param chart except ios_base basic_istream basic_ostream basic_ifstream basic_istringstream basic_iostream basic_ostringstream basic_ofstream basic_stringstream basic_fstream 5

6 The Stream I/O Class Hierarchy (cont.) High-level I/O classes basic_istream, basic_ostream, basic_iostream, and their derived classes Add local members and overloaded operators that are appropriately different for input and output stream respectively Class basic_istream and basic_ostream Adds methods for reading, writing and moving around in the stream Overloads I/O operators >> and << for built-in types Class basic_iostream Derived from both base classes and adds no additional members ios_base basic_ios basic_istream basic_ostream basic_ifstream basic_istringstream basic_iostream basic_ostringstream basic_ofstream basic_stringstream basic_fstream 6

7 Buffered I/O C++ Buffered I/O Classes Data are not directly read or written but rather pass through intermediate storage called buffer Buffered I/O classes basic_streambuf A base class for derived specialized stream buffer classes Having low-level methods for directly accessing the buffer Reading and writing the buffer, and moving around in the stream virtual methods to deal with buffer underflow and overflow basic_filebuf Data to write write chars Buffer basic_stringbuf write buffer (flush by newline or overflow) basic_streambuf Output basic_filebuf Each class is a template Contains constructors and methods for handling files with buffered I/O basic_stringbuf Contains constructors and methods for handling sequence of chars in storage 7

8 Two-Layered I/O Classes Design In C++, the buffered I/O hierarchy is distinct from the stream I/O hierarchy to separate the low-level and high-level I/O methods Low-level methods are in the buffered I/O classes Accesses and handles I/O stream buffers directly High-level methods are in the stream I/O classes Accesses the I/O stream indirectly by making calls to the low-level methods in the buffered I/O classes E.g., basic_ifstream Inherits high-level input methods from basic_istream Adds methods to open and close the file Also adds a data member of type basic_filebuf E.g., basic_ostringstream Inherits high-level output methods from basic_ostream Also adds a data member of type basic_stringbuf 8

9 Two-Layered I/O Classes Design (cont.) Application Application basic_ ifstream read basic_ ostring stream write basic_ filebuf sget basic_ string buf sput Buffer Buffer Read when the buffer underflows Written when the buffer overflows File Storage 9

10 C++ Headers for I/O Classes Header iosfwd iostream ios streambuf istream ostream iomanip sstream fstream Partial Description Contains forward declarations Declares cin, cout, manipulators, etc. Declares ios_base and basic_ios Declares basic_streambuf Declares basic_istream and basic_iostream Declares basic_ostream Declares parameterized manipulators Declares basic_stringbuf and the stringstream classes Declares basic_filebuf and the fstream classes Some of these headers include others 10

11 I/O Classes as Templates As mentioned previously, each I/O class is a template in the standard I/O hierarchy (except ios_base) E.g., the declaration for basic_ios is as follows template<class chart, class traits = char_traits<chart>> class basic_ios : public ios_base { }; //... chart: specifies the type to be use to represent a character Either built-in type char, wchar_t (wide character), or a user_defined type traits: specifies attributes of the character type I.e., template char_traits has typedefs and methods for chart» What is the end-of-file character» How the characters compare to each other» How they are copied or type-cast to/from other types, 11

12 Definitions of Common I/O Types The familiar I/O types are typedefs of the template I/O class instantiations in the <iosfwd> header Template arguments char as the first template argument char_traits<char> as the second argument by default Note cin and cout is declared as an object of istream and ostream respectively in the <iostream> header typedef basic_ios<char> ios; typedef basic_streambuf<char> streambuf; typedef basic_istream<char> istream; typedef basic_ostream<char> ostream; typedef basic_iostream<char> iostream; typedef basic_filebuf<char> filebuf; typedef basic_ifstream<char> ifstream; typedef basic_ofstream<char> ofstream; typedef basic_fstream<char> fstream; typedef basic_stringbuf<char> stringbuf; typedef basic_istringstream<char> istringstream; typedef basic_ostringstream<char> ostringstream; typedef basic_stringstream<char> stringstream; 12

13 The Common Base I/O Classes ios_base and basic_ios The standard I/O hierarchy is headed by two classes ios_base A nontemplate class that provides a description of the stream independent of the character set basic_ios A template class that provides a description of the stream that involves the character set The reason for splitting the basic functionality To minimize the size of the executable code Because code compiled from a nontemplate class is usually smaller than code from a template class 13

14 ios_base Direct or indirect base class for all of the standard I/O classes (except for the buffered I/O classes, basic_filebuf and basic_stringbuf) Declares I/O bitmask types, access methods, and I/O flags For I/O formatting information For describing the status of an open stream For indicating the how to move in a stream In addition, it provides some useful methods related to I/O Methods precision() and width() When invoked with no args, returns the current precision or width When invoked with an arg, sets the precision or width to the given value and returns the old precision or width Static method sync_with_stdio() Synchronizes the C++ I/O with the standard C I/O functions When C++ and C I/O libraries are intermixed, it should be invoked 14

15 Flags for I/O Format Information ios_base declares a bitmask type fmtflags used to specify I/O format information Constants for setting fmtflags Numeric bases: basefield, dec, hex, oct Justifications: adjustfield, left, right, internal Floating-point notations: floatfield, fixed, scientific I/O formats: boolalpha, uppercase, showbase, showpoint, showpos, skipws Etc.: unitbuf (flush any stream after a write) Access methods for fmtflags Accessing fmtflags (replace entire value): flags(), flags(val) Accessing individual bits: setf(val), unsetf(val) setf(val, ios_base::basefield) : val = dec, hex, or oct setf(val, ios_base::adjustfield) : val = left, right, or internal setf(val, ios_base::floatfield) : val = fixed, or scientific 15

16 Examples of Using I/O Formatting Flags // Saves the old flags and formats the cout with the new // flags as follows ios_base::fmtflags old_flags = cout.flags( ios_base::left ios_base::hex ios_base::showpoint ios_base::uppercase ios_base::fixed ); // setting a flag cout.setf( ios_base::showbase ); // is equivalent to cout.flags( cout.flags() ios_base::showbase ); // unsetting a flag cin.unsetf( ios_base::skipws ); // is equivalent to cin.flags( cin.flags() & ~ios_base::skipws ); 16

17 Examples of Using I/O Formatting Flags (cont.) cout.setf( ios_base::hex, ios_base::basefield ); cout << "Hex: " << 168 << '\n'; cout.setf( ios_base::oct, ios_base::basefield ); cout << "Octal: " << 168 << '\n'; Hex: a8 Octal: 250 cout.setf( ios_base::showbase ios_base::uppercase ); cout.setf( ios_base::hex, ios_base::basefield ); cout << "Hex: " << 168 << '\n'; cout.setf( ios_base::oct, ios_base::basefield ); cout << "Octal: " << 168 << '\n'; Hex: 0XA8 Octal:

18 Examples of Using I/O Formatting Flags (cont.) cout.width( 6 ); cout << -100 << '\n'; // default is right-justify cout.width( 6 ); cout.setf( ios_base::left, ios_base::adjustfield ); cout << -100 << '\n'; cout.width( 6 ); cout.setf( ios_base::right, ios_base::adjustfield ); cout << -100 << '\n'; // width reverts to 0 (default) // : effect of setw lasts only for the next I/O OP cout.setf( ios_base::right, ios_base::adjustfield ); cout << -100 << '\n';

19 Examples of Using I/O Formatting Flags (cont.) cout.width(6); cout.setf( ios_base::internal, ios_base::adjustfield ); cout << setfill( '0' ) << -100 << '\n'; const float log10_pi = ; cout.setf( ios_base::scientific, ios_base::floatfield ); cout << log10_pi << '\n'; cout.setf( ios_base::fixed, ios_base::floatfield ); cout << log10_pi << '\n'; // the value is rounded e

20 Other Flags Stream status flags for bitmask type ios_base::iostate (if set) badbit: bad input or output source eofbit: end of stream on input failbit: failure to read input or failure to produce expected output goodbit: input or output OK (the constant zero) Flags for bitmask type ios_base::openmode to describe the status of an open stream (if set) app: open for appending ate: open and move to end of stream binary: read and write as a binary stream in / out: open for input / output trunc: discard stream if it already exists Flags for bitmask type ios_base::seekdir to indicate how to seek (move) in a stream beg: seek from the beginning cur: seek from the current position end: seek from the end 20

21 Examples of Using Other Flags // Create an ofstream object associated with the file // out.dat, which is opened for appending // (writing at the end of the file) ofstream fout( "out.dat", ios_base::app ); // Moves the current position in the stream 10 bytes // forward out.seekp( 10, ios_base::cur ); // Moves the current position in the stream 10 bytes // forward from the beginning out.seekp( 10, ios_base::beg ); 21

22 basic_ios basic_ios is a template class derived from ios_base template <class chart, class traits = char_traits<chart>> class basic_ios : public ios_base { //... }; Contains methods to read, set, and clear the stream status flags rdstate(): returns the stream status clear(val): sets the stream status to val; if no argument, sets to 0 (goodbit) setstate(val): sets specified flags in the stream status good(): returns true if stream status is zero (goodbit); otherwise false eof(): returns true if eofbit is set; otherwise false fail(): returns true if failbit or badbit is set; otherwise false bad(): returns true if badbit is set; otherwise false 22

23 Examples of Using basic_ios Methods // Saves the current state for the cin ios_base::iostate cur_state = cin.rdstate(); Echoing integers from the standard input to the standard output int i; while (!cin.eof() ) { cin >> i; // eof bit set here cout << i << '\n'; // Warning: extra line is // printed } int i; do { cin >> i; // check if eofbit is set // after an input if (!cin.eof() ) cout << i << '\n'; } while (!cin.eof() ); 23

24 Clearing the Stream Status On many systems, a control character is interpreted as end-of-file E.g., [ctrl]+d in UNIX and [ctrl]+z in Windows To receive additional input after an EOF signal from the standard input, the eofbit flag can be cleared with the following statement cin.clear(); // clears all of the status flags for cin // including the eofbit 24

25 Operators Declared in basic_ios Class basic_ios newly declares the following operators template <class chart, class traits = char_traits<chart>> class basic_ios : public ios_base { //... operator void*() const; // type conversion OP bool operator!() const; //! OP //... }; Type conversion operator that converts basic_ios to void* The value of operator void*() is zero (null or false) if failbit or badbit is set Otherwise nonzero (true) Overloaded NOT operator! Returns true if failbit or badbit is set Otherwise false (e.g., (cin == true) (!cin == false)) if (cin >> i) { // check if standard input is ok //... process input } 25

26 Method fill() Class basic_ios has a method fill When invoked with no argument, e.g., fill(), returns the current fill character When invoked with an argument, e.g., fill(val), sets the fill character to val and returns the old fill character This has the same as the manipulator setfill(val) basic_ios::char_type old_fill = cout.fill( '0' ); // changes fill character (char_type : typedef of char) //... write to standard output cout.fill( old_fill ); // restores the original fill character 26

27 I/O Error Handling with the Stream Status Flags If an error occurs on I/O, one of the stream status flags is set A check for an error can be made using one of the basic_ios methods to read the status flags, or one of the operator void*() or operator!() Problem of this method An if statement for checking errors would have to follow every I/O operation cout << "Boola, boola!\n"; if ( cout.fail() ) { cerr << "Output operation failed\n"; //... } 27

28 I/O Error Handling with Exceptions The method exceptions in basic_ios can be used to request that certain I/O conditions throw exceptions When the argument is eofbit, badbit, failbit, or a combination, exceptions throws an exception of type ios_base::failure The argument goodbit can be used to deactivate throwing those I/O exceptions When invoked with no arguments, it returns the current I/O status flags The advantage of using exceptions all exceptions can be checked in a try block, no need to use if statements try { cout.exceptions( ios_base::failbit ); cout << "Boola, boola!\n"; } catch( ios_base::failure ) { cerr << "Output operation failed\n"; //... } 28

29 High-Level I/O Classes High-level I/O classes Base classes basic_istream, basic_ostream, and basic_iostream Derived classes of these classes File I/O classes basic_ifstream, basic_ofstream, and basic_fstream Character stream I/O classes basic_istringstream, basic_ostringstream, and basic_stringstream 29

30 basic_istream A template class derived from basic_ios template <class chart, class traits = char_traits<chart>> class basic_istream }; //... : virtual public basic_ios<chart, traits> { Provides high-level methods for input streams Such as get(), getline(), read(), peek(), putback(), ignore(), gcount(), seekg(), and tellg() Overloads operator >> for formatted inputs of built-in types 30

31 The get Method The method get is overloaded and so can be invoked in various way basic_istream<chart, traits>& get( char_type& c ); The next character, whitespace or not, is read into c Returns the stream on which it is invoked If there is no character to read, failbit is set int_type get(); The next character, whitespace or not, is returned (cf. fgetc in C) If there is no character to read, it returns an end-of-file flag appropriate to chart and sets failbit If chart is char, the end-of-file flag is EOF int_type is a typedef of some integer type, e.g., long int c; while ( ( c = cin.get() )!= EOF ) cout << c; 31

32 The getline Method The method getline is declared as follows basic_istream<chart, traits>& getline( char_type* b, An array b into which to write characters streamsize s, char_type d ); An integer value s that bounds the number of characters (should be equal to the length of b to avoid array overflow) An end-of-line marker d (defaults to a newline if omitted) The method read characters into b until it Reaches end-of-file (eofbit is set and returns 0), encounters end-of-line marker d (discard the marker), or stores s 1 characters (failbit is set) After it stops reading, getline adds a null terminator to the array and returns the stream on which it is invoked 32

33 Example of Using getline #include <iostream> #include <fstream> using namespace std; const int BuffSize = 133; int main() { ifstream in; ofstream out; char buff[ BuffSize ]; in.open( "infile.dat" ); out.open( "outfile.dat" ); while ( in.getline( buff, BuffSize ) ) out << buff << "\n\n"; // writes double space return 0; } 33

34 The read Method The method read is used to read binary data (cf. fread in C) basic_istream<chart, traits>& read( char_type* a, Reads characters and stores them in the array a until n characters are read, or end-of-file occurs (failbit is set) streamsize n ); After it stops reading, read returns the stream on which it is invoked No terminator character is used, no null terminator is placed in the array a The number of characters actually read can be determined with the method gcount streamsize gcount(); returns the number of characters read by the last unformatted input method 34

35 Manipulating Input Streams The method peek is declared as follows int_type peek(); Returns the next character from the stream but does not remove it from the stream If no characters remain to be read, returns end-of-file The method putback is declared as follows basic_istream<chart, traits>& putback( char_type c ); Put the character c back to the stream (cf. ungetc in C) And returns the stream on which it is invoked The method ignore is declared as follows basic_istream<chart, traits>& ignore( int count = 1, int_type stop ); Removes and discards count characters, or all characters until end-offile, or all characters up to and including stop from the stream And returns the stream on which it is invoked 35

36 Handling Input Stream Position Markers The method seekg sets the position within the input stream (cf. fseek in C) basic_istream<chart, traits>& seekg( off_type off, ios_base::seek_dir dir ); Moves the input stream position marker off bytes from dir (one of ios_base::cur, ios_base::beg, or ios_base::end) And returns the stream on which it is invoked When used with a file, the file should be opened as binary file basic_istream<chart, traits>& seekg( pos_type pos ); Sets the input stream position marker to location pos And returns the stream on which it is invoked When used with a file, the file need not to be opened as binary file The method tellg is declared as follows (cf. ftell in C) pos_type tellg(); Returns the location of the input stream position marker Note that off_type and pos_type are typedefs of integer 36

37 Formatted Input Operator >> The class basic_istream overloads the right-shift operator for formatted input of built-in types, the declaration is as follows basic_istream<chart, traits>& operator>>( built_in_type& v ); A built_in_type value is read into the variable v And returns the stream on which it is invoked The input operator >> can be chained Because operator>> returns the stream and associates from the left E.g., cin >> i >> j; == (cin >> i) >> j; == { cin >> i; cin >> j; } The types can be handled by >> bool int signed char* unsigned int unsigned char* long chart* unsigned long signed char float unsigned char double chart long double short void* unsigned short 37

38 Examples of Using >> // chart = char& is used to read one character // (default is to skip whitespaces unlike scanf in C) char c; while ( cin >> c ) cout << c; // for the input x y z cout << '\n'; // prints xyz // echoes the standard input to the standard output char c; cin.unsetf( ios_base::skipws ); // clear skipws flag while ( cin >> c ) cout << c; cout << '\n'; // chart = char* is used to read a C-stype string char a[ 80 ]; cin.width( 80 ); // avoids overflow in the array a cin >> a; // read all non-ws chars up to the next ws char // or read at most (width 1) characters 38

39 Type Checking for Input Data For integer types If the first non-whitespace character is not a digit or a sign failbit is set, no further data can be read until failbit is cleared For floating-point types If the first non-whitespace character is not a digit, a sign, or a decimal point failbit is set, no further data can be read until failbit is cleared int main() { int val; bool ok; string line; cout << hex; for ( ; ; ) { cout << "Enter an integer (negative to quit): "; ok = true; cin >> val; // if val is illegal, // cin convert to false if (!cin ) { } cout << "Bad input. Redo."; cin.clear(); // clear failbit getline( cin, line ); // clear input stream ok = false; } if ( ok ) if ( val < 0 ) break; else cout << val << '\n'; } return 0; 39

40 basic_ostream A template class derived from basic_ios template <class chart, class traits = char_traits<chart>> class basic_ostream }; //... : virtual public basic_ios<chart, traits> { Provides high-level methods for output streams Such as put(), write(), seekp(), tellp(), and, flush() Overloads operator << for formatted outputs of built-in types 40

41 The put Method The method put writes the character passed to the output stream (cf. fputc in C) basic_ostream<chart, traits>& put( char_type c ); Writes the character c to the output stream Returns the (updated) stream on which it is invoked char c = $ ; cout.put( c ); // is equivalent to cout << c; 41

42 The write and flush Methods The method write is used to write binary data (cf. fwrite in C) basic_ostream<chart, traits>& write( const char_type* a, streamsize m ); Writes m characters from the array a to the output stream If the operation fails, badbit is set Returns the (updated) stream on which it is invoked The method flush flushes the buffer (cf. fflush in C) basic_ostream<chart, traits>& flush(); Returns the (updated) stream on which it is invoked 42

43 Handling Output Stream Position Markers The method seekp sets the position within the output stream (cf. fseek in C) basic_ostream<chart, traits>& seekp( off_type off, ios_base::seek_dir dir ); Moves the output stream position marker off bytes from dir (one of ios_base::cur, ios_base::beg, or ios_base::end) And returns the (updated) stream on which it is invoked When used with a file, the file should be opened as a binary file basic_ostream<chart, traits>& seekp( pos_type pos ); Sets the output stream position marker to location pos And returns the (updated) stream on which it is invoked When used with a file, there is no need to open the file as a binary file The method tellp is declared as follows (cf. ftell in C) pos_type tellp(); Returns the location of the output stream position marker 43

44 Formatted Output Operator << The class basic_ostream overloads the left-shift operator for formatted output of built-in types, the declaration is as follows basic_ostream<chart, traits>& operator<<( built_in_type v ); Write built_in_type value v to the output stream And returns the (updated) stream on which it is invoked The input operator << can also be chained Because operator<< returns the stream and associates from the left E.g., cout << i << j; == (cin << i) << j; == { cin << i; cin << j; } The types can be handled by << bool short const signed char* unsigned short const unsigned char* long const char* unsigned long const chatt* float signed char double unsigned char long double char void* chart 44

45 Examples of Using << float x = ; cout << "x = " << x << \n&x = << static_cast<void*>(&x) << \n'; x = &x = 0012FF7C 45

46 basic_iostream Class basic_iostream publicly inherits from both basic_istream and basic_ostream Its entire declaration is as follows template <class chart, class traits = char_traits<chart>> class basic_iostream }; : public basic_istream<chart, traits>, public basic_ostream<chart, traits> { public : explicit basic_iostream( basic_streambuf<chart, traits>* ); virtual ~basic_iostream(); Provides high-level methods for input/output streams 46

47 Manipulators A manipulator is a function that either directly or indirectly modifies a stream (introduced in sec. 2.2) A manipulator is used with the overloaded input operator >> or output operator << E.g., manipulator hex causes subsequent input or output to be hexadecimal int i = 10; cout << hex << i << \n ; // prints a Note that manipulators with arguments need to include header iomanip, with no arguments iostream 47

48 Manipulators Introduced in Sec. 2.2 A manipulator permanently changes the state of the stream to which it is applied except that effect of setw lasts only for the next I/O operation 48

49 Using I/O Formatting Flags vs. Using Manipulators cout.setf( ios_base::showbase ios_base::uppercase ); cout.setf( ios_base::hex, ios_base::basefield ); cout << "Hex: " << 168 << '\n'; cout.setf( ios_base::oct, ios_base::basefield ); cout << "Octal: " << 168 << '\n'; Hex: 0XA8 Octal: 0250 cout << setiosflags( ios_base::showbase ios_base::uppercase ) << hex << "Hex: " << 168 << '\n' << oct << "Octal: " << 168 << '\n'; Hex: 0XA8 Octal:

50 I/O Operators and Manipulators without Arguments A manipulator without arguments (e.g., endl) can be used as an argument of I/O operators I.e., when used, a manipulator without arguments is passed as a function argument of an I/O operator Then, the operator invokes the manipulator, which has, as a function, one argument of type basic_ostream& or basic_istream& and returns the (updated) stream argument Finally, the operator returns the stream on which the I/O operation is executed 50

51 I/O Operators and Manipulators without Arguments (cont.) Definition of operator<< for manipulators template < class chart, class traits > basic_ostream< chart, traits >& basic_ostream< chart, traits >::operator<<( basic_ostream& ( *f )( basic_ostream& ) ) { return f( *this ); // invokes the manipulator } E.g., cout << endl; Equivalent to cout.operator<<( endl ); Definition of endl as a function ostream& endl( ostream& os ) { os << '\n'; return os.flush(); } 51

52 Writing User-Defined Manipulators without Arguments Using the previously explained technique, it is possible to write our own manipulators with no arguments // a user-defined manipulator that rings // the bell once ostream& bell( ostream& os ) { return os << "\a"; // Linux bell char } //... cout << bell; // rings the bell 52

53 Writing User-Defined Manipulators with Arguments Consider writing a manipulator that takes an argument E.g., manipulator bell( n ) that rings the bell n times Such a manipulator could be invoked as cout << bell( 10 ); Because the function call operator ( ) has greater precedence than <<, the compiler, at first, tries to invoke function bell( n ) with argument 10, then the wrong version of << would be invoked In this case, the compiler invokes bell(10) and then incorrectly invokes operator<<( basic_ostream& ) due to its return value (cout) rather than invokes operator<<( basic_ostream& (*f)( int ) ); So that the compiler can unambiguously choose the correct version of <<, the type of the value returned by bell must be different from the types of arguments expected by all the other versions of << 53

54 Writing User-Defined Manipulators with Arguments (cont.) To avoid the previous problem Define a wrapper class omanip for a manipulator function template< class Typ, // type of manipulator s argument class chart, class traits = char_traits<chart> > struct omanip { Typ n; // actual manipulator s argument n void ( *f )( basic_ostream< chatt, traits >&, Typ ); // actual manipulator f omanip( void ( *f1 )( basic_ostream< chatt, traits >&, Typ ), Typ n1 ) : f( f1 ), n( n1 ) { } }; Overload the operator << as a top-level function for the wrapper omanip, not a manipulator template< class chart, class traits, class Typ > basic_ostream< chart, traits >& operator<<( basic_ostream< chart, traits >& os, const omanip< Typ, chart >& sman ) { ( sman.f )( os, sman.n ); // invoke the actual manipulator return os; 54 }

55 Writing User-Defined Manipulators with Arguments (cont.) // a user-defined manipulator function that rings // the bell n times void bell_ringer( ostream& os, int n ) { for ( int i = 0; i < n; i++ ) os << "\a"; } // a manipulator that returns the wrapper of the // manipulator function omanip< int, char > bell( int n ) { return omanip< int, char >( bell_ringer, int n ); } cout << bell( 10 ); // rings the bell 10 times // operator<<( cout, bell(10) ) invokes // operator<<( basic_ostream&, omanip<int, char> ) 55

Chapter 12 - C++ Stream Input/Output

Chapter 12 - C++ Stream Input/Output Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3

More information

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits> The C++ I/O System I/O Class Hierarchy (simplified) ios_base ios / \ istream ostream \ / iostream ifstream fstream ofstream The class ios_base -- public variables and methods The derived classes istream,

More information

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

Module 11 The C++ I/O System

Module 11 The C++ I/O System Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

Rogue Wave Standard C++ Library Iostreams and Locale User s Reference

Rogue Wave Standard C++ Library Iostreams and Locale User s Reference Rogue Wave Standard C++ Library Iostreams and Locale User s Reference (Part B) Rogue Wave Software Corvallis, Oregon USA Copyright 1996 Rogue Wave Software, Inc. All rights reserved. Rogue Wave Standard

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

I/O Streams and Standard I/O Devices (cont d.)

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

Fig: iostream class hierarchy

Fig: iostream class hierarchy Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

UNIT V FILE HANDLING

UNIT V FILE HANDLING UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

UEE1303(1070) S 12 Object-Oriented Programming in C++

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

Note also that this proposed resolution adds missing constructor descriptions for stack<>.

Note also that this proposed resolution adds missing constructor descriptions for stack<>. Document No: N3266 = 11-0036 Previous version: N3112 = 10-0102 Date: 2011-03-22 Project: Programming Language C++ References: WG21 N3092, SC 22 N4512: ISO/IEC FCD 14882 Reply to: Nicolai Josuttis nico@josuttis.de

More information

C++ does not, as a part of the language, define how data are sent out and read into the program

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

Streams in C++ Stream concept. Reference information. Stream type declarations

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

Iostreams Issues List Library Clause 27

Iostreams Issues List Library Clause 27 By: Philippe Le Mouël Doc. No.: X3J16/96-0099 Rogue Wave Software Inc. WG21/N0917 philippe@roguewave.com Date: May 25 1996 Iostreams Issues List Library Clause 27 Revision History Pre-Stockholm Post-Santa-Cruz

More information

n1099 Document No.: J16/ WG21/N1099 Date: 17 July 1997 Programming Language C++

n1099 Document No.: J16/ WG21/N1099 Date: 17 July 1997 Programming Language C++ Document No.: J16/97-0061 WG21/N1099 Date: 17 July 1997 Project: Reply-To: Programming Language C++ Steve Rumsby steve@maths.warwick.ac.uk Iostreams WP changes for London ===============================

More information

Input/Output Streams: Customizing

Input/Output Streams: Customizing DM560 Introduction to Programming in C++ Input/Output Streams: Customizing Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne Stroustrup]

More information

Unit-V File operations

Unit-V File operations Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the

More information

CS11 Advanced C++ Lecture 2 Fall

CS11 Advanced C++ Lecture 2 Fall CS11 Advanced C++ Lecture 2 Fall 2006-2007 Today s Topics C++ strings Access Searching Manipulation Converting back to C-style strings C++ streams Error handling Reading unformatted character data Simple

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing Input Data 1 Streams 2 Streams Conceptual Model of a Stream Associating a File Stream with a File Basic Stream Input Basic Stream Output Reading Single Characters: get() Skipping and Discarding Characters:

More information

Writing a Good Program. 7. Stream I/O

Writing a Good Program. 7. Stream I/O Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)

More information

Java IO and C++ Streams

Java IO and C++ Streams Java IO and C++ Streams October 22, 2004 Operator Overloading in C++ - 2004-10-21 p. 1/31 Outline Java IO InputStream/OutputStream FilterInputStream/FilterOutputStream DataInputStream/DataOutputStream

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

CS201 Solved MCQs.

CS201 Solved MCQs. 15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Copyright 2008 Pearson Addison-Wesley. All rights reserved.

More information

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

p0448r1 - A strstream replacement using span<chart> as buffer

p0448r1 - A strstream replacement using span<chart> as buffer p0448r1 - A strstream replacement using span as buffer Peter Sommerlad 2017-06-07 Document Number: p0448r1 (N2065 done right?) Date: 2017-06-07 Project: Programming Language C++ Audience: LWG/LEWG

More information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Revising the wording of stream input operations

Revising the wording of stream input operations Revising the wording of stream input operations Document #: P1264R0 Date: 2018-10-07 Project: Programming Language C++ Audience: LWG Reply-to: Louis Dionne 1 Abstract The wording in

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

p0448r0 - A strstream replacement using span<chart> as

p0448r0 - A strstream replacement using span<chart> as p0448r0 - A strstream replacement using span as buffer Peter Sommerlad 2016-10-14 Document Number: p0448r0 (N2065 done right?) Date: 2016-10-14 Project: Programming Language C++ Audience: LWG/LEWG

More information

Module C++ I/O System Basics

Module C++ I/O System Basics 1 Module - 36 C++ I/O System Basics Table of Contents 1. Introduction 2. Stream classes of C++ 3. Predefined Standard Input/Output Streams 4. Functions of class 5. Functions of class

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Object Oriented Programming In C++

Object Oriented Programming In C++ C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

Advanced I/O Concepts

Advanced I/O Concepts Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations

More information

10/23/02 21:20:33 IO_Examples

10/23/02 21:20:33 IO_Examples 1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

Introduction. Lecture 5 Files and Streams FILE * FILE *

Introduction. Lecture 5 Files and Streams FILE * FILE * Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and

More information

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

Week 3: File I/O and Formatting 3.7 Formatting Output

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

More information

Chapter 11 Customizing I/O

Chapter 11 Customizing I/O Chapter 11 Customizing I/O Bjarne Stroustrup www.stroustup.com/programming Overview Input and output Numeric output Integer Floating point File modes Binary I/O Positioning String streams Line-oriented

More information

IOStreams Issues List Library Clause 27

IOStreams Issues List Library Clause 27 By: Philippe Le Mouël Doc. No.: X3J16/96-0009 Rogue Wave Software Inc. WG21/N0827 philippe@roguewave.com Date: January 30 1996 IOStreams Issues List Library Clause 27 Revision History Pre-Santa Cruz Post-Tokyo

More information

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Object Oriented Programming Using C++ UNIT-3 I/O Streams File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.

More information

We will exclusively use streams for input and output of data. Intro Programming in C++

We will exclusively use streams for input and output of data. Intro Programming in C++ C++ Input/Output: Streams The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: 1 istream

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University [CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7 Seungkyu Lee Assistant Professor, Dept. of Computer Engineering Kyung Hee University Input entities Keyboard, files Output entities Monitor, files Standard

More information

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Consider the following example where a base class has been derived by other two classes:

Consider the following example where a base class has been derived by other two classes: Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

Standard I/O in C and C++

Standard I/O in C and C++ Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

What we will learn about this week:

What we will learn about this week: What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1 I/O Streams as an Introduction

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

File I/O Christian Schumacher, Info1 D-MAVT 2013

File I/O Christian Schumacher, Info1 D-MAVT 2013 File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential

More information

Chapter 12: Advanced File Operations

Chapter 12: Advanced File Operations Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes: C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading

More information

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Course Title: Object Oriented Programming Full Marks: 60 20 20 Course No: CSC161 Pass Marks: 24 8 8 Nature of Course: Theory Lab Credit Hrs: 3 Semester: II Course Description:

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Chapter 11 Customizing I/O

Chapter 11 Customizing I/O Chapter 11 Customizing I/O Bjarne Stroustrup www.stroustrup.com/programming Overview Input and output Numeric output Integer Floating point File modes Binary I/O Positioning String streams Line-oriented

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on

More information

Proposed Resolution for CH 15: Double check copy and move semantics of classes due to new rules for default move constructors and assignment operators

Proposed Resolution for CH 15: Double check copy and move semantics of classes due to new rules for default move constructors and assignment operators Document No: N3112 = 10-0102 Date: 2010-08-06 Project: Programming Language C++ References: WG21 N3092, SC 22 N4512: ISO/IEC FCD 14882 Reply to: Nicolai Josuttis nico@josuttis.de Proposed Resolution for

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

Developed By : Ms. K. M. Sanghavi

Developed By : Ms. K. M. Sanghavi Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream

More information

Generate error the C++ way

Generate error the C++ way Reference informa9on Lecture 3 Stream I/O Consult reference for complete informa9on! UNIX man- pages (available on exam): man topic man istream man ostream ios, basic_string, stringstream, ctype, numeric_limits

More information

Chapter 12. Streams and File I/O

Chapter 12. Streams and File I/O Chapter 12 Streams and File I/O Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag settings Introduction Streams Special objects Deliver

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Chapter 11 Customizing I/O

Chapter 11 Customizing I/O Chapter 11 Customizing I/O Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using C++

More information

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversation / Casting Name Constant - const, #define X When You Mix Apples and Oranges: Type Conversion Operations

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file? CS162 External Data Files 1 External Files So far, all of our programs have used main memory to temporarily store

More information

Item 1: Switching Streams

Item 1: Switching Streams ITEM1_11new.fm Page 1 Tuesday, November 27, 2001 12:12 PM Item 1: Switching Streams ITEM 1: SWITCHING STREAMS DIFFICULTY: 2 What s the best way to dynamically use different stream sources and targets,

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course

More information

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() { Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead,

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Lecture 3 The character, string data Types Files

Lecture 3 The character, string data Types Files Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',

More information

Setting Justification

Setting Justification Setting Justification Formatted I/O 1 Justification - Justification refers to the alignment of data within a horizontal field. - The default justification in output fields is to the right, with padding

More information

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information