开发者

Reverse part of a stream (between markers) using effectors or manipulators

开发者 https://www.devze.com 2023-01-25 15:28 出处:网络
Greetings! I\'d like to make small program what reverses part of a stream between markers using stream effectors and/or manipulators For exampl开发者_StackOverflow中文版e:

Greetings!

I'd like to make small program what reverses part of a stream between markers using stream effectors and/or manipulators For exampl开发者_StackOverflow中文版e:

From this: cout << "something" << revstream::start << "asdf" << 3.14 << revstream::end << "something";

To this: something41.3fdsasomething

I'd like it to work not just on the standard cout and I'd like to embed them several times.

I'm new in c++ and my main problems are: - I can't create a new stream to store what is inside the markers - How to reverse the temp stream?

I tried so many things and I stuck here:

class revstream {

 public:

    static ostream& start(ostream &os) { 
        //do the reversing
    return ???;
    }    

    static ostream& end(ostream &os) {

    return reversedstream;
    }   
};


You can do this, but it's ugly as butt:

class revstream: public std::ostream
{
public:
    static std::ostream &start(std::ostream &os)
    {
        return *(new revstream(os));
    }

    static std::ostream &end(std::ostream &rev)
    {
        revstream *actual_rev= dynamic_cast<revstream *>(&rev);

        // logic for reversing output goes here

        std::ostream &result= actual_rev->os;
        delete actual_rev;

        return result;
    }

    revstream(std::ostream &in_os): std::ostream(&reversebuf), os(in_os)
    {
        return;
    }

    std::ostream &os;
    std::stringbuf reversebuf;
};

Your ostream manipulator has to return a reference to ostream, so you have to allocate within revstream::start.


This isn't how you asked to go about it, but I would approach the problem in a different way. Instead of writing some kind of extension to the streams, why not just write a function that reverses a string?

#include <string>
#include <iostream>
using namespace std;

string reverse(const string& str)
{
    return string(str.rbegin(), str.rend());
}

int main()
{
    cout << reverse("asdf") << "\n";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消