1

I am trying to have a function myCout that have a string among its argument. This string is meant to set the alignment of the output. That is is if we have "left" as argument cout<<std::left; should be executed .

I have attached my code below.

ostream & myAlign (string str) {

        if (str == "left")
            return  std ::left ; 
        else 
            return std::right ;
}

template <class T>
void myCout (int width, char fill, T var, string a) {

    cout << setw(width) << setfill(fill) << setprecision(2) << myAlign(a) << std:: fixed << var << "\t" <<flush ;    
    return ;
}

Thank you for your help in advance

jpw
  • 44,361
  • 6
  • 66
  • 86
  • 2
    You might want to check e.g. [this reference of I/O manipulators](http://en.cppreference.com/w/cpp/io/manip), especially the ones about the [manipulators you use](http://en.cppreference.com/w/cpp/io/manip/left). – Some programmer dude Nov 14 '13 at 07:37
  • 4
    @TobiasWärre Wut? I'm pretty sure you can, since you have defined [`operator==`](http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp), see case (7). – luk32 Nov 14 '13 at 07:44
  • 2
    @TobiasWärre Not sure where you're getting your information, or how you got an upvote. Comparing a `std::string` with a string literal is perfectly OK. – john Nov 14 '13 at 07:46
  • @TobiasWärre: that is *not* correct. – jalf Nov 14 '13 at 08:02
  • @luk32, Well look at that, I must have missed it... – Tobias Wärre Nov 15 '13 at 08:40

1 Answers1

4

IO manipulators are not magic, but they can be odd to think about. There are several ways to do this, this being just one of them, mimicking the behavior it appears you're looking for..

#include <iostream>
#include <iomanip>

class myAlign
{
public:
    explicit myAlign(const std::string& s)
        : fmt((s == "left") ? std::ios::left : std::ios::right)
    {}

private:
    std::ios::fmtflags fmt;

    friend std::ostream& operator <<(std::ostream& os, const myAlign& arg)
    {
        os.setf(arg.fmt);
        return os;
    }
};

int main(int argc, char *argv[])
{
    std::cout << myAlign("left") << std::setw(10) << "12345" << std::endl;
    std::cout << myAlign("right") << std::setw(10) << "67890" << std::endl;
    return 0;
}

Output

12345     
     67890

Note: A similar but considerably more complex related question can be found here.

Community
  • 1
  • 1
WhozCraig
  • 65,258
  • 11
  • 75
  • 141