简体   繁体   中英

How can I modify strings that are passed to cout?

Suppose I want to rot13 every string passed to cout (or another ostream), so that, say cout<<"Foo Bar Baz.;" (or even cout<<rot13<<"Foo Bar Baz."; ) outputs Sbb One Onm.

How would I go about doing that?

(My first idea was to replace cout's streambuf with a streambuf-derived class that would do all the work. But seeing as the original streambuf is responsible for directing stuff to the console... that didn't work out at all.)

You can write your own stream that overload operator<< for char*, std::string and others and prints a transformed text.

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

class ostream_rot13 : public basic_ostream <char, char_traits<char> >
{
public:
    ostream_rot13(std::basic_streambuf<char, char_traits<char> >* sb) 
    : basic_ostream<char, char_traits<char> >(sb) {}

    ostream_rot13& operator<<(const char* text)
    {
        std::string s(text);

        int rot=13;
        std::transform(std::begin(s), std::end(s), ostream_iterator<char>(*this), [rot] (char c) { 
            if(c >= 'a' && c <= 'z')
                return 'a' + (c + rot - 'a') % 26;
            else if(c >= 'A' && c <= 'Z')
                return 'A' + (c + rot - 'A') % 26;

            return (int)c;
        });

        return *this;
    }
};

The next step is to declare a global variable of this type and then a macro that replaces cout with the new variable.

ostream_rot13 cout_rot13(std::cout.rdbuf());

#define cout cout_rot13

And then all instances of cout will become cout_rot13.

int main() 
{
    cout << "Foo Bar Baz";

    return 0;
}

Couldn't you wrap cout's streambuf in your own, forwarding all calls to the wrapped buffer?
You'd only need to do some encoding before forwarding the "put" calls into the wrapped streambuf.

It's a lot of work for a little rot13, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM