带前缀填充的C ++输出

时间:2012-08-11 18:43:30

标签: c++ cout

如何在C ++中打印带填充的字符串?具体我想要的是:

cout << "something in one line (no prefix padding)"
cout << "something in another line (no prefix padding)"
set_padding(4)
    cout << "something with padding"
    cout << "something with padding"
set_padding(8)
        cout << "something with padding"
        cout << "something with padding"

也就是说,我会多次打电话给cout,我不想一直打电话给setw(len) << ""

3 个答案:

答案 0 :(得分:4)

我想您可以为您预制处理器:

#include <iostream>
#define mout std::cout << std::string(width,' ')
#define mndl "\n" << std::string(width,' ')

int width=0;

int main()
{
    mout << "Hello" << std::endl; 

    width = 8;

    mout << "World." << mndl << "Next line--still indented";
    // more indented lines...
}

答案 1 :(得分:3)

如下:

class IndentedOutput
{
public:
    IndentedOutput()
    {
        m_indent = 0;
    }

    void setIndent(unsigned int indent)
    {
        m_indent = indent;
    }

    template <typename T>
    std::ostream& operator<< (const T& val)
    {
        return (std::cout << std::string(m_indent,' ') << val);
    }

private:
    unsigned int m_indent;
};

你可以像这样使用它:

IndentedOutput ind;

int i =0;
ind << "number is " << i++ << '\n';
ind << "number is " << i++ << '\n';
ind.setIndent(4);
ind << "number is " << i++ << '\n';
ind << "number is " << i++ << '\n';
ind.setIndent(6);
ind << "number is " << i++ << '\n';
ind << "number is " << i++ << '\n';
ind.setIndent(0);
ind << "number is " << i++ << '\n';

答案 2 :(得分:-1)

http://www.cplusplus.com/reference/iostream/manipulators/

编辑:对不起,我有点空手。我的意思是研究iomanip如何工作,我知道你知道sets(n)&lt;&lt; &#34;&#34;

使用iomanip作为快速和脏实现的基线,这就是我想出的:

#include <iostream>
#include <iomanip>
#include <string>

class setpw_ {
  int n_;
  std::string s_;
public:
  explicit setpw_(int n) : n_(n), s_("") {}
  setpw_(int n, const std::string& s) : n_(n), s_(s) {}

  template<typename classT, typename traitsT>
  friend std::basic_ostream<classT, traitsT>&
  operator<<(std::basic_ostream<classT, traitsT>& os_, const setpw_& x) {
    os_.width(x.n_);
    os_ << "";
    if ( x.s_.length()){
      os_ << x.s_;
    }
    return os_;
  }
};

setpw_ setpw(int n) { return setpw_(n); }
setpw_ indent(int n, const std::string& s) { return setpw_(n, s); }

int
main(int argc, char** argv) {
  std::cout << setpw(8) << "Hello, World" << std::endl;
  std::cout << indent(8,   "----^BYE^---") << std::endl;
  return 0;
}