c++coutiomanip

c++ iomanip table formatting


I'm in trouble with iomanip. I think a simplified code can explain everything better than words.

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

struct Dog {
  std::string name;
  int age;
};

std::ostream& operator<<(std::ostream& os, Dog dog) {
  return os << dog.name << ", " << dog.age << "yo";
}

int main() {
  Dog dog;
  dog.name = "linus";
  dog.age = 10;

  std::cout
    << std::left << std::setw(20) << std::setfill(' ') << "INFO"
    << std::left << std::setw(20) << std::setfill(' ') << "AVAILABLE" << std::endl;

  std::cout
    << std::left << std::setw(20) << std::setfill(' ') << dog
    << std::left << std::setw(20) << std::setfill(' ') << "yes";

  std::cin.get();
}

I would print a well formatted table, but my output is bad aligned. In simple words when I cout my dog, setw and setfill works only on dog.name (because of the nature of operator<<) and the result is something like

INFO                AVAILABLE
linus               , 10yoyes

instead of

INFO                AVAILABLE
linus, 10 yo        yes

Obviously I could modify operator<<, appending just one string to os but in my real case I have to change tons of complex definitions (and I prefer avoiding such changes! :D)

Any idea?


Solution

  • The setw manipulator sets the field width of the next output which in this case is dog.name. There's really no way around it if you want to use the stream directly in the overloaded function.