0

How can I print an string with padding in C++? Specifically what I want is:

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"

That is, I'll call cout many times and I don't want to call setw(len) << "" all the time.

GSerg
  • 76,472
  • 17
  • 159
  • 346
JohnTortugo
  • 6,356
  • 7
  • 36
  • 69

3 Answers3

4

I suppose you could just make the pre-processor type it for you:

#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...
}
3

How about something like:

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

And the you can use it like this:

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';
Asaf
  • 4,317
  • 28
  • 48
-1

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

EDIT: Sorry, I was a little short handed. What I meant was to research how iomanip works, I know you are aware of sets(n) << ""

Using iomanip as a baseline for a quick and dirty implementation, this is what I came up with:

#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;
}
dans3itz
  • 1,605
  • 14
  • 12