Custom C Stream Manipulator to Alter Subsequent Stream Items
In C , the hex manipulator can be used to convert a number to its hexadecimal representation. However, what if you need to modify not only the current item but also subsequent items on the stream?
Creating the plusone Manipulator
To create a manipulator that increments the next numeric value on the stream, follow these steps:
1. Store State on Each Stream:
Use iword and geti() to store state on each stream.
inline int geti() { static int i = ios_base::xalloc(); return i; }
2. Define Manipulator Functions:
Create functions to set and unset the stored state.
ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; } ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; }
3. Intercept Numeric Output:
Create a my_num_put facet to intercept numeric output and apply the stored increment.
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())); } };
4. Test the Manipulator:
Use the manipulators to increment the next numeric value and display the results.
int main() { // outputs: 11121011 cout.imbue(locale(locale(),new my_num_put)); cout << add_one << 10 << 11 << add_none << 10 << 11; }
Reset Single-Use Increment:
If you want to increment only the next number, reset the stored state after each call to do_put.
The above is the detailed content of How Can You Create a Custom C Stream Manipulator to Modify Subsequent Stream Items?. For more information, please follow other related articles on the PHP Chinese website!