C ++ iomanip表格式 [英] c++ iomanip table formatting

查看:67
本文介绍了C ++ iomanip表格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 iomanip 的麻烦.我认为简化的代码可以比单词更好地解释一切.

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

我会打印格式正确的表,但是我的输出对齐不正确.简而言之,当我 cout 我的狗时, setw setfill 仅对dog.name起作用(由于 operator<< ),结果类似于

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

代替

INFO                AVAILABLE
linus, 10 yo        yes

很明显,我可以修改 operator<< ,仅将一个 string 附加到 os ,但在我的实际情况下,我必须更改复杂的定义(我更喜欢避免此类更改!:D)

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)

有什么主意吗?

推荐答案

setw 操作器设置 next 输出的字段宽度,本例中为dog.name .如果您想直接在重载的函数中使用流,实际上没有办法解决.

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.

这篇关于C ++ iomanip表格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆