Custom Stream Manipulation in C++ - Manipulators with No Argument
(Page 2 of 4 )
When your operation requires no additional parameters, and you want, for instance, to pack a couple of these kinds of objects together, the task is quite trivial. The idea is to write a function that will conform to the following example:
ios_base& scientify(ios_base& in)
{
// make the flag modifications on in
return (in);
}
An additional improvement can be made; it is, however, not mandatory. As you expect that this will be heavily used, you may decide to make them inline functions in order to speed up your application. Also, note that the insertion and extraction operators are not defined for the “ios_base” class, so we need to use the internal function setf to apply the flags.
Inside the setf function, the flags can be combined with the bitwise or operator. Look over my example below:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
inline ios_base& scientify(ios_base& in)
{
in.setf( ios_base::showpos );
in.setf( ios_base::scientific | ios_base::showpoint);
return(in);
}
inline ios_base& resetFloat(ios_base& in)
{
in.setf( 0, ios_base::floatfield);
return(in);
}
int main( ) {
ios_base::fmtflags oldFlags = cout.flags( );
double i = 3.165;
cout << setprecision( 3);
cout << scientify << i << endl;
cout<< resetFloat << i << endl;
cout.flags(oldFlags);
}
+3.165e+000
+3.17
Press any key to continue . . .
The output speaks for itself if you are already familiar with manipulators in general. During the “scientify” manipulator declaration, I wanted to point out that you can combine them and apply them in a row. The second function uses the setf function's overload, where the second argument stays for flags to be set off. The ios_base::float is a combination of flags that includes all float-related modifications. Simply calling the unsetf would raise the same result.
Next: Solution for Multiple Arguments >>
More C++ Articles
More By Gabor Bernat