1

我试图有myCout 一个在其参数中包含一个字符串的函数。该字符串用于设置输出的对齐方式。也就是说,如果我们有"left"as 参数 cout<<std::left;应该被执行。

我在下面附上了我的代码。

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 ;
}

提前谢谢你的帮助

4

1 回答 1

4

IO 操纵器并不神奇,但想想它们可能很奇怪。有几种方法可以做到这一点,这只是其中一种,模仿你正在寻找的行为。

#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;
}

输出

12345     
     67890

注意:可以在此处找到一个类似但相当复杂的相关问题。

于 2013-11-14T08:12:44.033 回答