0

I need to convert a ostream's object in a ostringstream's object. This is the code:

//gerarchia_view.h
class bagaglio_view{
private:
    std::ostream& os;
    std::string data;
public:
    bagaglio_view();
    std::string print_bagaglio(const bagaglio &b) const;
};

//gerarchia_view.cpp
bagaglio_view::bagaglio_view():data(" "),os(std::cout){
}

std::string bagaglio_view::print_bagaglio(const bagaglio& b) const{
    os<<b; // operator << is overloaded
    std::ostringstream* oss=static_cast<std::ostringstream*>(&os);
    return oss->str(); // down-cast, segm fault
}

I need the function

std::string bagaglio_view::print_bagaglio(const bagaglio& b) const;

return the string that is in std::ostream os. How can I solve that? I tried dynamic_cast and using a std::ostringstream in substution of std::ostream, but operator<< doesn't work.

BottCode
  • 31
  • 11
  • 2
    Does your `std::ostream&` actually refer to a `std::ostringstream` or something else? – Galik Mar 04 '16 at 18:57
  • no but it's construct in bagaglio_view::bagaglio_view() – BottCode Mar 05 '16 at 00:14
  • That constructor doesn't attach your `std::ostream&` to a `std::ostringstream` it attaches it to ` std::cout` which is **not** a `std::ostringstream`. If you cast it to the wrong type its undefined behavior, it breaks. – Galik Mar 05 '16 at 00:33
  • Ok. So, what I use in substitution of std::cout ? – BottCode Mar 05 '16 at 10:24
  • You say you want to *"return the string that is in std::ostream os"* but the problem is that `std::ostream` objects don't usually contain strings. For example `std::ofstream` sends its output to the hard disk. `std::cout` sends its output to the console. They do not keep internal string copies of everything they output. It is only `std::ostringstream` that does that. **So what are you trying to achieve?** Maybe we can find another way to do it? – Galik Mar 05 '16 at 10:39

0 Answers0