c++manipulators

How to write my own manipulator?


Let's suppose I want to write my own manipulator for input and output.

cin >> mymanip >> str;

or

cout << mymanip << str;

What I want that mymanip does is toggle case the caracters I read from input and assigns the result to one string.

So, if I type "QwErTy" I get "qWeRtY" in the string.

This is a very basic task with one function, but i want to learn more about manipulators.

Can someone give a clue?

Thank you.


Solution

  • The way is a little tricky - but it can be done, you can add own manipulator for stream.

    First, you need your toggle:

    class toggle_t {};
    constexpr toggle_t toggle;
    

    Next - the version for ostream (the case for istream is very similar...):

    After putting toggle to ostream - you need some special object:

    struct toggled_ostream
    {
        std::ostream& os;
    };
    
    inline toggled_ostream operator << (std::ostream& os, toggle_t)
    {
        return { os };
    }
    

    Beware, that someone might put togglein wrong place: cout << toggle << 123 - so it should work for all other types as ordinary stream:

    template <typename T>
    std::ostream& operator << (toggled_ostream tos, const T& v)
    {
        return tos.os << v;
    }
    

    So - for char types (like char, const char*, std::string) write your toggle overloads. I am giving you version for char - it shouldn't be a problem to write version for "longer" types:

    std::ostream& operator << (toggled_ostream tos, char v)
    {
        char c = std::isupper(v) ? std::tolower(v)
                                 : std::islower(v) ? std::toupper(v) : v;
        return tos.os << c;
    }
    

    Working demo.