ios Formatting Flags
Understand the usage of ios formatting flags available in the C++ language.
We'll cover the following...
Problem
Write a program that demonstrates the use of ios
formatting flags for floating-point precision, and the output field width, padding character.
Coding solution
Here is a solution to the problem above.
Press + to interact
// ios formatting flags#include <iostream>#include <iomanip>int main( ){int i = 52 ;float a = 425.0 ;float b = 123.500328 ;char str[ ] = "Dream. Then make it happen!" ;std :: cout.setf ( std :: ios :: unitbuf ) ;std :: cout.setf ( std :: ios :: showpos ) ;std :: cout << i << std :: endl ;std :: cout.setf ( std :: ios :: showbase ) ;std :: cout.setf ( std :: ios :: uppercase ) ;std :: cout.setf ( std :: ios :: hex, std :: ios :: basefield ) ;std :: cout << i << std :: endl ;std :: cout.setf ( std :: ios :: oct, std :: ios :: basefield ) ;std :: cout << i << std :: endl ;std :: cout.fill ( '0' ) ;std :: cout << "Fill character: " << std :: cout.fill( ) << std :: endl ;std :: cout.setf ( std :: ios :: dec, std :: ios :: basefield ) ;std :: cout.width ( 10 ) ;std :: cout << i << std :: endl ;std :: cout.setf ( std :: ios :: left, std :: ios :: adjustfield ) ;std :: cout.width ( 10 ) ;std :: cout << i << std :: endl ;std :: cout.setf ( std :: ios :: internal, std :: ios :: adjustfield ) ;std :: cout.width ( 10 ) ;std :: cout << i << std :: endl ;std :: cout << i << std :: endl ; // without width ( 10 )std :: cout.width ( 10 ) ;std :: cout << str << std :: endl ;std :: cout.width ( 40 ) ;std :: cout << str << std :: endl ;std :: cout.setf ( std :: ios :: left, std :: ios :: adjustfield ) ;std :: cout.width ( 40 ) ;std :: cout << str << std :: endl ;std :: cout.precision ( 6 ) ;std :: cout << "Precision: " << std :: cout.precision( ) ;std :: cout.setf ( std :: ios :: showpoint ) ;std :: cout.unsetf ( std :: ios :: showpos ) ;std :: cout << std :: endl << a ;std :: cout.unsetf ( std :: ios :: showpoint ) ;std :: cout << std :: endl << a ;std :: cout.setf ( std :: ios :: fixed, std :: ios :: floatfield ) ;std :: cout << std :: endl << b ;std :: cout.setf ( std :: ios :: scientific, std :: ios :: floatfield ) ;std :: cout << std :: endl << b ;b = 5.375 ;std :: cout.precision ( 14 ) ;std :: cout.setf ( std :: ios :: fixed, std :: ios :: floatfield ) ;std :: cout << std :: endl << b ;std :: cout.setf ( std :: ios :: scientific, std :: ios :: floatfield ) ;std :: cout << std :: endl << b << std :: endl ;std :: cout.unsetf ( std :: ios :: showpoint ) ;std :: cout.unsetf ( std :: ios :: unitbuf ) ;return 0 ;}
Explanation
The on/off flags are simple. They can be turned on through the setf( )
function and off through the unsetf( )
function.
The flags that can be set/unset in this manner include skipws
, showbase
, showpoint
, uppercase
, showpos
, unitbuf
...