This item was added on: 2003/03/22
cout
has many manipulators that allow specific formatting of output. One can set flags explicitly with std::ios_base
member functions:
#include <iostream>
int main()
{
std::cout.setf ( std::ios_base::right, std::ios_base::basefield );
std::cout.width ( 10 );
std::cout<< "Test" <<std::endl;
}
Some of the flags that can be controlled are:
skipws
left
right
internal
boolalpha
dec
hex
oct
scientific
fixed
showbase
showpoint
showpos
uppercase
adjustfield
basefield
floatfield
unitbuf
These flags can be manipulated with member functions such as:
flags()
flags ( fmtflags f )
setf ( fmtflags f )
setf ( fmtflags f, fmtflags mask );
unsetf( fmtflags mask )
width()
width ( streamsize wide )
fill()
fill ( Ch ch )
precision()
precision ( streamsize n )
Alternatively, output manipulators can be used.
#include <iostream>
#include <iomanip>
int main()
{
std::cout<< std::setiosflags ( std::ios_base::right )
<< std::setw ( 10 ) << "Test" <<std::endl;
}
Manipulators tend to be cleaner and safer than explicitly setting flags. Some of the standard manipulators declared in <ios>, <iostream> and <iomanip> are:
boolalpha
noboolalpha
showbase
noshowbase
showpoint
noshowpoint
showpos
noshowpos
skipws
noskipws
uppercase
nouppercase
left
right
internal
dec
hex
oct
fixed
scientific
endl
ends
flush
ws
resetiosflags ( fmtflags f )
setiosflags ( fmtflags f )
setbase ( int base )
setfill ( int ch )
setprecision ( int n )
setw ( int n )
Those that are not shown to take arguments are to be used as follows:
#include <iostream>
#include <iomanip>
int main()
{
int val = 123;
std::cout<< val <<" "<< std::oct << val <<" "<< std::hex << val <<std::endl;
}
The user programmer also has the ability to define their own manipulators, this is a more advanced topic, however, so it will be discussed later.Credit: Prelude