0

如何在 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) << ""

4

3 回答 3

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...
}
于 2012-08-11T19:14:47.727 回答
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';
于 2012-08-11T19:53:54.203 回答
-1

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

编辑:对不起,我有点人手不足。我的意思是研究 iomanip 的工作原理,我知道你知道 sets(n) << ""

使用 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;
}
于 2012-08-11T18:54:13.843 回答