设置重载运算符的精度<<

时间:2014-02-14 20:11:52

标签: c++

我已经重载了运算符<<在我的程序中打印有关产品的数据。

ostream& operator<< (ostream &out, const Product& p) {
    return out << '\t' << (int)p.code << "\tR$ " << p.price << '\t' << p.name;
}

但我需要将p.price的精度更改为2位小数。

我已经尝试过 out.setprecision(2),但它没有用。

这是打印产品的部分:

cout << this->items[i] << endl;

结果:

253 R$ 13 Paçoca

我需要R$ 13,00

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

  

我已经重载了运算符&lt;&lt;在我的程序中打印有关产品的数据。 ......

您只需将其插入std::ostream& std::operator<<(std::ostream& out, ...)函数调用链:

即可
ostream& operator<< (ostream &out, const Product& p) {
    return out << '\t' << (int)p.code << "\tR$ " 
               << std::fixed << std::setprecision(2) 
               << p.price << '\t' << p.name;
}

您可能还需要调整一些本地化设置以获得,(而非.)以使您的小数点分隔符正确。

  

我已经尝试过 out.setprecision(2),但它没有用。

原因是setprecision(int)不是std::ostream接口的方法,而是由以下位组成的全局函数(从MinGW GCC 4.6.2实现中窃取):

struct _Setprecision { int _M_n; };

// This is what's actually called (both functions below):
inline _Setprecision 
    setprecision(int __n) { return { __n }; }

template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>& 
operator<<(basic_ostream<_CharT, _Traits>& __os, _Setprecision __f)
{ 
    // Note you can alternatively call std::ostream::precision() function
    __os.precision(__f._M_n);
    return __os; 
}