Search⌘ K
AI Features

Usage of Standard Manipulator

Explore the use of standard manipulators in C++ to format output streams efficiently. Understand how manipulators simplify stream formatting commands and control aspects like alignment, number base, precision, and flushing. This lesson helps you apply common manipulators to produce clean, readable output, enhancing your data handling skills in C++ programming.

We'll cover the following...

Problem

Write a program using manipulators to produce similar output as in this lesson.

Coding solution

Here is a solution to the problem above.

C++
// Standard manipulators usage
#include <iostream>
#include <iomanip>
int main( )
{
int i = 52 ;
float a = 425.0 ;
float b = 123.500328f ;
char str[ ] = "Dream. Then make it happen!" ;
std :: cout << setiosflags ( std :: ios ::unitbuf | std :: ios ::showpos ) ;
std :: cout << i << std :: endl ;
std :: cout << setiosflags ( std :: ios ::showbase | std :: ios ::uppercase ) ;
std :: cout << std :: hex << i << std :: endl ;
std :: cout << std :: oct << i << std :: endl ;
std :: cout << std :: setfill ( '0' ) ;
std :: cout << "Fill character:" << std :: cout.fill( ) << std :: endl ;
std :: cout << std :: dec << std :: setw ( 10 ) << i << std :: endl ;
std :: cout << std :: setiosflags ( std :: ios ::left )
<< std :: dec << std :: setw ( 10 ) << i << std :: endl ;
std :: cout << std :: setiosflags ( std :: ios ::internal )
<< std :: dec << std :: setw ( 10 ) << i << std :: endl ;
std :: cout << i << std :: endl ;
std :: cout << std :: setw ( 10 ) << str << std :: endl ;
std :: cout << std :: setw ( 40 ) << str << std :: endl ;
std :: cout << std :: setiosflags ( std :: ios ::left ) << std :: setw ( 40 ) << str << std :: endl ;
std :: cout.precision ( 6 ) ;
std :: cout << "Precision: " << std :: cout.precision( ) ;
std :: cout << std :: setiosflags ( std :: ios ::showpoint ) << std :: resetiosflags ( std :: ios ::showpos )
<< std :: endl << a ;
std :: cout << std :: resetiosflags ( std :: ios ::showpoint )
<< std :: endl << a ;
std :: cout << std :: setiosflags ( std :: ios ::fixed ) << std :: endl << b ;
std :: cout << std :: resetiosflags ( std :: ios ::showpoint | std :: ios ::unitbuf ) <<std :: endl ;
return 0 ;
}

Explanation

Calling the member functions of the ios class to set the formatting data of the stream is a little tedious. The actions of these functions can be more easily (and cleanly) duplicated using manipulators. When we use manipulators, the formatting instructions are inserted directly into a stream.

...