ostream Problem

Discussion in 'C++' started by Mike Copeland, May 1, 2014.

  1. I am trying to combine std::left and std::setw() as a single
    function. The following code ignores the "left" manipulator. What am I
    doing wrong? TIA

    struct leftsetw // combined functions (left/width)
    {
    leftsetw(int w) : width(w) {}
    int width;
    };
    ostream &operator<<(ostream &o, const leftsetw &a)
    {
    o.left, o.width(a.width);
    return o;
    }

    ostringstream oss;
    oss.str(""); oss << "Test " << leftsetw(12) << 42;
     
    Mike Copeland, May 1, 2014
    #1
    1. Advertisements

  2. Try calling the function instead of evaluating the function pointer:

    o.left(),
    V
     
    Victor Bazarov, May 1, 2014
    #2
    1. Advertisements

  3. Mike Copeland

    Stefan Ram Guest

    #include <iostream>
    #include <sstream>

    struct leftsetw
    { int const width;
    leftsetw( int const width ): width{ width } {} };

    ::std::eek:stream & operator<<
    ( ::std::eek:stream & ostream, const leftsetw & leftsetw )
    { ostream.width( leftsetw.width );
    ostream.setf( ::std::ios_base::left, std::ios_base::adjustfield );
    return ostream; }

    int main()
    { ::std::eek:stringstream ostringstream;
    ostringstream << '|' << leftsetw( 2 )<< 3 << '|';
    ::std::cout << ostringstream.str() << '\n'; }
     
    Stefan Ram, May 1, 2014
    #3
  4. Mike Copeland

    Stefan Ram Guest

    ::std::left( o )

    N3797, 27.5.6.2
     
    Stefan Ram, May 1, 2014
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.