1.2 I/O Formatting

The following methods can be used to manipulate the output.

setw ( int )

width of the next field

<iostream>



setprecision (int)

precision for the next fixed decimal number

<iomanip>



setbase (int)

number base for the next integer number

<iomanip>



setfill ( char )

filling for space unused by the next field

<iomanip>

<..out.cxx..>
 #include<ostream.h>
 #include<iomanip.h>
 using namespace std;
 
 int main() {
   cout << 123.456789 << endl
        << setw(9)    << 123.456789 << endl
        << setw(12)   << 123.456789 << endl;
 
   cout << setprecision (1) << 123.456789 << endl
        << setprecision (3) << 123.456789 << endl
        << setprecision (8) << 123.456789 << endl
        << setprecision (9) << 123.456789 << endl;
 
   cout << setbase( 8 )  << 100 << endl
        << setbase( 16 ) << 100 << endl ;
 
   cout << setfill( '.' ) << setw(10) << 123 << endl;
   return 0;
 }
-_-_-
123.457  
  123.457  
     123.457  
1e+02  
123  
123.45679  
123.456789  
144  
64  
........7b

The following methods of <iostream> can be used to manipulate flags that control the I/O format.

fmtflags setf ( fmtflags fmtfl )

set the flags specified in the argument




fmtflags unsetf ( fmtflags fmtfl )

clear the flags specified in the argument




fmtflags setf ( fmtflags fmtfl,
fmtflags mask )

set the flags that are common to fmtfl and mask
clear the flags referenced in fmtfl but not in mask




setiosflags
resetiosflags
( fmtflags fmtfl )

flag for next fieldd

The following flags are offered by <iomanip.h>

ios::skipws

skip whitespace in input

<..spaces.cxx..>
 #include <iostream>
 #include<iomanip.h>
 using namespace std;
 
 int main() {
       char c;
   cin.unsetf( ios::skipws );
   while ( cin >> c ){
     cout << c;
   }
   cout << endl;
   return 0;
 }
-_-_-
Five words  
in two lines.  
ios::left
ios::right

justified output

<..justify.cxx..>
 #include <iostream>
 #include<iomanip.h>
 using namespace std;
 
 int main() {
   cout.setf ( ios_base::left );
   cout << setw(10) << 123 << endl;
   cout.setf ( ios_base::right );
   cout << setw(10) << 123 << endl;
   return 0;
 }
-_-_-
123  
       123
ios::basefield

(de) activate



ios::dec
ios::oct
ios::hex

number system



ios::uppercase

for letters in hexadecimal numbers



ios::basefield

ios_base::hex | ios_base::oct | ios_base::dec

<..base.cxx..>
 #include <iostream>
 using namespace std;
 int main () {
 
   cout.setf ( ios_base::hex, ios_base::basefield );
   cout.setf ( ios_base::showbase );
   cout << 100 << endl;
   cout.unsetf ( ios_base::showbase );
   cout << 100 << endl;
 
   return 0;
 }
-_-_-
0x64  
64