Using setw(), setiosflags(), resetiosflags() manipulators in C++ programming for output formatting

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using setw(), setiosflags(), resetiosflags() manipulators in C++ programming

To show: How to format the C++ standard output using setw(), setiosflags(), resetiosflags() manipulators

 

// using setw(), setiosflags(), resetiosflags() manipulators and setf and unsetf member functions

#include <iostream>

#include <iomanip>

using namespace std;

 

void main(void)

{

long p = 123456789L;

 

// L - literal data type qualifier for long

// F - float, UL unsigned long integer

cout<<"The default for 10 fields is right justified:\n"

<<setw(10)<<p

<<"\n\nUsing member function\n"

<<"---------------------\n"

<<"\nUsing setf() to set ios::left:\n"<<setw(10);

 

cout.setf(ios::left,ios::adjustfield);

cout<<p<<"\nUsing unsetf() to restore the default:\n";

cout.unsetf(ios::left);

cout<<setw(10)<<p

<<"\n\nUsing parameterized stream manipulators\n"

<<"---------------------------------------\n"

<<"\nUse setiosflags() to set the ios::left:\n"

<<setw(10)<<setiosflags(ios::left)<<p

<<"\nUsing resetiosflags() to restore the default:\n"

<<setw(10)<<resetiosflags(ios::left)

<<p<<endl;

 

return;

}

 

Output example:

 

The default for 10 fields is right justified:

123456789

Using member function

---------------------

Using setf() to set ios::left:

123456789

Using unsetf() to restore the default:

123456789

Using parameterized stream manipulators

---------------------------------------

Use setiosflags() to set the ios::left:

123456789

Using resetiosflags() to restore the default:

123456789

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index