有没有一种方法可以将setw的某些值设为默认值?

时间:2019-06-08 17:06:16

标签: c++ stream setw

我想使用相同的setw参数在流中进行多次插入。有没有一种方法可以不复制“ << setw(2)”,而只需将其设置一次并保留它?

有问题的部分的示例:

cout << 'a' << setw(5) << 'b' << 'c' << (var1 > var2)?'d' :'a';

输出

a    bcd

我想要的是

cout << 'a' << setw(5) << 'b' << setw(5) << 'c'
            << setw(5) << (var1 > var2)?'d' :'a';

有输出

a    b    c    d

1 个答案:

答案 0 :(得分:-1)

setw不粘,因此每次How to allow setw apply to all the following stdout? 都必须说出来

这是解决您问题的丑陋方法:

#include <iostream>
#include <iomanip>

using namespace std;

template <typename T>
class ConstantWidth {
public:
    ConstantWidth(T i) : i(i) { }
    friend ostream& operator<<(ostream& out, ConstantWidth<T> const& ei){
    out << setw(5) << ei.i;
    return out;
    }
private:
    T i;
};
using myInt = ConstantWidth<int>;
int main()
{
   myInt i = 2;
   std::cout<<"Here is an int " << i;

}