2014-02-14 72 views
2

我已经超载了运算符< <以在我的程序中打印有关产品的数据。设置超载运算符的精度<<

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),但它没有工作。

这是打印产品的一部分:我需要它是R$ 13,00

253 R$ 13 Paçoca

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

和结果。

任何想法?

+1

只是IT连锁: '... << setprecision(2)<< ...'! –

+1

'cout << std :: fixed << std :: setprecision(2)<< p.price;' – jrok

+0

如果你确实是指'253'(这是'(int)p.code'的值)应该也走开,只是不输出它。 –

回答

3

我已经超载了运营商< <以打印有关我的程序中的产品的数据。 ...

你只需将其插入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),但它didin't工作。

的原因是,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; 
}