【问题标题】:How to execute std::left from a string如何从字符串执行 std::left
【发布时间】:2013-11-14 07:34:38
【问题描述】:

我试图有一个函数myCout,它的参数中有一个字符串。该字符串用于设置输出的对齐方式。也就是说,如果我们有 "left" 作为参数 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 ;
}

提前感谢您的帮助

【问题讨论】:

  • 您可能需要检查例如this reference of I/O manipulators,尤其是关于manipulators you use的那些。
  • @TobiasWärre Wut?我很确定你可以,因为你已经定义了operator==,见案例(7)。
  • @TobiasWärre 不确定您从哪里获得信息,或者您如何获得支持。将 std::string 与字符串文字进行比较是完全可以的。
  • @TobiasWärre:这是正确的。
  • @luk32,看那个,我一定错过了......

标签: c++


【解决方案1】:

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

注意:一个类似但相当复杂的相关问题can be found here

【讨论】:

  • 非常感谢您的回答,真的很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
相关资源
最近更新 更多