TITLE: creating simple output manipulators (Newsgroup: comp.lang.c++, 18 May 2000) FINSTER: FinsterBaby (bsprings@bestweb.net) : Just as an exercise I would like to create a manipulator called : space which accepts an int and would just print X spaces. e.g. : : cout << space(5) << "Hello World\n"; KHUEL: kuehl@ramsen.informatik.uni-konstanz.de (Dietmar Kuehl) Basically, you create a simple class with a constructor taking your argument and then you create an output operator for this class just doing the manipulation: struct space { space(int n): no(n) {} int no; }; std::ostream& operator<< (std::ostream& os, space const& s) { std::fill_n(std::ostream_iterator(os), s.no, ' '); return os; } Of course, you might want to improve the implementation of the manipulator to become more efficient if you are using it a lot... This would look like this: std::ostream& operator<< (std::ostream& os, space const& s) { std::ostream::sentry kerberos(os); if (kerberos) std::fill_n(std::ostreambuf_iterator(os), s.no, ' '); return os; } The difference between the two implementations is basically that the first version constructs two 'sentry' objects for each space inserted while the second version only creates one 'sentry'. Also, the first version uses basically statements like os << ' ' << str; where 'os' is the first argument to the iterator and 'str' is the second one which is defaulted to "" to insert a single space. The second approach uses the underlying stream buffer directly, ie. uses os.rdbuf().sputc(' '); Probably you won't see a difference but if you are using 'space' a lot, there will be performance hit from using the first version. ... and the second one does not look that much more complex. Anyway, the important part was to show how to create a manipulator with an argument: Actually, there is no trick to it like for the manipulators taking no arguments... _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com