You are on page 1of 37

| 


I/O System Basics

‡ supports two complete I/O systems:

± I/O system inherited from C

± object-oriented I/O system defined by C++

‡ console I/O and disk I/O, are actually just different


perspectives on the same mechanism.
‡ I/O library is supported by the header ¢ 
.
heed for new I/O system
‡ C's I/O system knows nothing about
objects.
‡ C++ I/O system operates on user-defined
objects.
‡ The C I/O is supported by C++ only for
compatibility.
C++ Streams
‡ the C++ I/O system operates through streams.

‡ A à is a logical device that either produces or


consumes information.

‡ A stream is linked to a physical device.

‡ All streams behave in the same way.


± (i.e) same function that writes to a file to write to the printer
or to the screen
The C++ Stream Classes

‡ In ¢ 
complicated set of class
hierarchies , that supports I/O Operations are
defined .
‡ The I/O classes begin with a system of template
classes.
‡ C++ creates two specializations of the I/O
template classes:
± one for 8-bit characters and another for wide
characters.
‡ There are two different template class
hierarchies.
‡ r  
r  -> supports basic, low-
level input and output operations
‡ Used widely in advanced I/O programming.
‡ r    Commonly used , it provides
formatting, error checking, and status
information related to stream I/O.
r   

r   
r  
r   

(input) (output) (input/output)


K
   |     | 
|  r  |  r  | 
basic_streambuf streambuf wstreambuf
basic_ios ios wios
basic_istream istream wistream
basic_ostream ostream wostream
basic_iostream iostream wiostream
basic_fstream fstream wfstream
basic_ifstream ifstream wifstream
basic_ofstream ofstream wofstream
C++'s Predefined Streams

Stream Meaning Default Device


cin Standard input Keyboard
cout Standard output Screen
cerr Standard error output Screen
clog Buffered version of cerr Screen

‡ four built-in streams are automatically opened, when


execution begins
‡ Streams  ,  , and  correspond to C's  ,
 , and  
‡ By default they communicate with the console
:ormatted I/O

‡ To format the display to the user.


‡ There are two different ways,
± directly access members of the class
± special functions called 
 àcan be
used
:ormatting Using the ios Members

‡ :or each stream there are set of format flags


that control the way information is formatted.
‡ class declares a bitmask enumeration called

  it contains the values.

adjustfield basefield boolalpha dec


fixed floatfield hex internal
left oct right scientific
showbase showpoint showpos skipws
unitbuf uppercase
‡    leading white-space characters are discarded

‡    output is left justified (output is right justified by


default)

‡   output to be displayed in octal.(default decimal)

‡ r   the base of numeric values

‡     characters are displayed in uppercase

‡     floating-point numeric values are displayed


using scientific notation.

‡    floating-point values are displayed using normal


notation.
‡ The ,  , and     r   .

‡ The  , , and       .

‡ The    and   fields =>   .


Setting the :ormat :lags

‡  function, member of  is used to set the flags.

fmtflags setf(fmtflags 
 à);

‡ General format:
± stream.setf( ios::showpos );

Any predefined stream an enumerated constant defined by the class


üinclude <iostream>
using namespace std;
int main()
{
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout << 100.0; // displays +100.0
return 0;
}

// You can OR together two or more flags,


cout.setf(ios::showpoint | ios::showpos);
Clearing :ormat :lags

‡ unsetf function member of  is used to


clear the flags

‡ Prototype:
void unsetf(fmtflags 
 à);
üinclude <iostream>
using namespace std;
int main()
{
cout.setf(ios::uppercase | ios::scientific);
cout << 100.12; // displays 1.0012E+02
cout.unsetf(ios::uppercase); // clear uppercase
cout << " \n" << 100.12; // displays 1.0012e+02
return 0;
}
An Overloaded :orm of setf( )

‡ Prototype:
fmtflags setf(fmtflags 
 à , fmtflags 
 à);

‡ only the flags specified by 


 à are
affected
‡ first cleared and then set according to the
flags specified by 
 à .
üinclude <iostream>
using namespace std;
int main( )
{
cout.setf(ios::showpoint | ios::showpos, ios::showpoint);
cout << 100.0; // displays 100.0, not +100.0
return 0;
}

üinclude <iostream>
using namespace std;
int main()
{
cout.setf(ios::hex, ios::basefield);
cout << 100; // this displays 64
return 0;
}
üinclude <iostream>
using namespace std;
int main()
{
cout.setf(ios::showpos, ios::hex); // error, showpos not set
cout << 100 << '\n'; // displays 100, not +100
cout.setf(ios::showpos, ios::showpos); // this is correct
cout << 100; // now displays +100
return 0;
}
Examining the :ormatting :lags
‡ Prototype:
fmtflags flags( );
‡ Used to know the current format settings.
‡ :lags cannot be altered.
‡ Is a member function of base class 
üinclude <iostream> // check each flag
using namespace std; for(i=0x4000; i; i = i >> 1)
void showflags() ; if(i & f) cout << "1 ";
int main() else cout << "0 ";
{ cout << " \n";
// show default condition of format flags }
showflags();
cout.setf(ios::right | ios::showpoint |   
ios::fixed);
showflags(); 
return 0; 
}
// This function displays the status of the
format flags.
void showflags()
{
ios::fmtflags f;
long i;
f = (long) cout.flags(); // get flag settings
Setting All :lags
üinclude <iostream>
using namespace std;
void showflags();
int main()
{
// show default condition of format flags
showflags();
// showpos, showbase, oct, right are on, others off
long f = ios::showpos | ios::showbase | ios::oct | ios::right;
cout.flags(f); // set all flags
showflags();
return 0;
}
Using width( ), precision( ), and fill( )

‡ Prototype:
l streamsize width(streamsize —);
l streamsize precision(streamsize );
l char fill(char 2 );
üinclude <iostream>   
using namespace std;
int main() 10.12
{ *****10.12
cout.precision(4) ; *******Hi!
cout.width(10); 10.12*****
cout << 10.12345 << "\n"; // displays 10.12
cout.fill('*');
cout.width(10);
cout << 10.12345 << "\n"; // displays *****10.12

// field width applies to strings, too


cout.width(10);
cout << "Hi!" << "\n"; // displays *******Hi!
cout.width(10);
cout.setf(ios::left); // left justify
cout << 10.12345; // displays 10.12*****
return 0;
}
Using Manipulators to :ormat I/O

‡ I/O manipulators parallel member functions of


the class.
‡ To access manipulators you should include
¢ 
 
Some manipulators
//program using manipulators //program using flags
üinclude <iostream> üinclude <iostream>
üinclude <iomanip> üinclude <iomanip>
using namespace std; using namespace std;
int main()
int main()
{
{
cout << hex << 100 << endl;
cout << setfill('?') << setw(10) <<2343.0; cout.setf(ios::hex, ios::basefield);
return 0; cout << 100 << "\n"; // 100 in hex
} cout.fill('?');
cout.width(10);
   cout << 2343.0;
 return 0;
!!!!!!"# # }

Advantage of manipulators : more compact code to be written


‡ the    manipulator can also be used.

üinclude <iostream>
üinclude <iomanip>
using namespace std;
int main()
{
cout << setiosflags(ios::showpos);
cout << setiosflags(ios::showbase);
cout << 123 << " " << hex << 123;
return 0;
}
Overloading << and >>

‡ These operators can be overloaded to perform I/O


operations.

‡ ¢¢output operator => à    à à

‡ input operator =>  2     2 à


Inserters
‡ Skeleton :
ostream &operator¢¢(ostream &à 
2
àà  )
{
//   à 
return à ;
}
‡ 
=> output stream.
‡ 1st parameter =>reference to 
.
‡ 2nd parameter => reference to an object
‡ This function should return à 
     r   r

class phonebook {
public: // Display name and phone number
char name[80]; ostream &operator<<(ostream
int areacode; &stream, phonebook o)
int prefix; {
int num; stream << o.name << " ";
phonebook(char *n, int a, int p, int stream << "(" << o.areacode << ") ";
nm) stream << o.prefix << "-" << o.num <<
{ "\n";
strcpy(name, n); return stream; // must return stream
areacode = a; }
prefix = p;
num = nm;
}
};
üinclude <iostream>
üinclude <cstring> int main()
using namespace std; {
class phonebook { phonebook a("Ted", 111, 555, 1234);
public: phonebook b("Alice", 312, 555, 5768);
char name[80]; phonebook c("Tom", 212, 555, 9991);
int areacode; cout << a << b << c;
int prefix; return 0;
int num; }
phonebook(char *n, int a, int p, int nm)
{   
strcpy(name, n); K %%%"#
areacode = a; &  #"%%%%'(
prefix = p; K
""%%%)))
num = nm;
} };
$  
  
r 
ostream &operator<<(ostream &stream, phonebook o)
{
stream << o.name << " ";
stream << "(" << o.areacode << ") ";
stream << o.prefix << "-" << o.num << "\n";
return stream; 
  

}
‡ Inserter is not a member function (to invoke a
member the object should be on the   side)

‡ when you overload inserters, the    


à  and the    r  of
the class

‡ Inserters are not member functions, hence to


access the private data, they can be made as
  of the class.
üinclude <iostream> int main()
üinclude <cstring> {
using namespace std; phonebook a("Ted", 111, 555, 1234);
class phonebook { phonebook b("Alice", 312, 555, 5768);
char name[80];    phonebook c("Tom", 212, 555, 9991);
int areacode; cout << a << b << c;
int prefix; return 0;
int num; }
public:
phonebook(char *n, int a, int p, int nm)
{
strcpy(name, n);
areacode = a;
prefix = p;
num = nm;
}
friend ostream &operator<<(ostream &stream, phonebook o);
};

$  


  
r 

X
ostream &operator<<(ostream &stream, phonebook o)
{
stream << o.name << " ";   
   
stream << "(" << o.areacode << ") ";  r
stream << o.prefix << "-" << o.num << "\n";
return stream; 
  

}
Extractors

‡ Skeleton:
istream &operator (istream &à 2
àà  )
{
//    2 
return à ;
}
‡ 
=> input stream.
‡ 1st parameter =>reference to 
.
‡ 2nd parameter => reference to an object
Extractor for phonebook class:

istream &operator>>(istream &stream, phonebook &o)


{
cout << "Enter name: ";
stream >> o.name; /* Cout is used when the program interacts
cout << "Enter area code: "; with console else these can be removed */
stream >> o.areacode;
cout << "Enter prefix: ";
stream >> o.prefix;
cout << "Enter number: ";
stream >> o.num;
cout << "\n";
return stream;
}

It can be made safe by defining it like,



  ¢¢*+ 
*,