In C++, to print a number in hexadecimal you do this:
int num = 10;
std::cout << std::hex << num; // => 'a'
I know I can create a manipulator that just adds stuff to the stream like so:
std::ostream& windows_feed(std::ostream& out)
{
out << "\r\n";
return out;
}
std::cout << "Hello" << windows_feed; // => "Hello\r\n"
However, how can I create a manipulator that, like 'hex', modifies items to come on the stream? As a simple example, how would I create the plusone manipulator here?:
int num2 = 1;
std::cout << "1 + 1 = " << plusone << num2; // => "1 + 1 = 2"
// note that the value stored in num2 does not change, just its display above.
std::cout << num2; // => "1"
The
hex
,dec
andoct
manipulators simply change thebasefield
property of the existingstream
.See C++ Reference for more deatail about these manipulators.
As posted in Neil Butterworth's answer, you would need to extend the existing stream classes, or create your own, in order to have manipulators that affect future values inserted into the stream.
In the example of your
plusone
manipulator, the stream object would have to have an internal flag to indicate that one should be added to all inserted values. Theplusone
manipulator would simply set that flag, and the code to handle stream insertion would check that flag before inserting numbers.