Creating Custom Stream Manipulators that Modify Subsequent Stream Items
Introduction:
In C , stream manipulators are useful for altering the format and behavior of stream operations. This article explores how to create custom manipulators that can modify items that follow them on the stream.
Creating an "Add One" Manipulator:
Consider the "plusone" manipulator described in the question:
int num2 = 1; std::cout << "1 + 1 = " << plusone << num2; // "1 + 1 = 2" std::cout << num2; // "1"
To implement this manipulator, we need to achieve two things:
Storing State:
We use stream word storage to associate a state with a stream:
inline int geti() { static int i = ios_base::xalloc(); return i; } ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; } ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; }
Modifying Numeric Output:
We define a custom number facet:
struct my_num_put : num_put<char> { iter_type do_put(iter_type s, ios_base& f, char_type fill, long v) const { return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); } iter_type do_put(iter_type s, ios_base& f, char_type fill, unsigned long v) const { return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); } };
This facet increments numbers before outputting them, based on the state stored in the stream.
Testing the Manipulator:
int main() { // outputs: 11121011 cout.imbue(locale(locale(),new my_num_put)); cout << add_one << 10 << 11 << add_none << 10 << 11; }
Limiting the Increment to the Next Item:
To only increment the next item, reset the stream state to 0 after each do_put operation.
The above is the detailed content of How Can You Create a Custom Stream Manipulator to Modify Subsequent Stream Items in C ?. For more information, please follow other related articles on the PHP Chinese website!