简体   繁体   English

为什么setw和width对于ostringstream不起作用?

[英]Why setw and width does not work for ostringstream?

I have the following code: 我有以下代码:

template<typename _Tp>
std::string string_from_number(_Tp number, int precision = 5)
{
  std::ostringstream oss;
  oss.width(precision+1);
  oss<<number;
  return oss.str();
}

However the string length is not 5 as expected, but stays the default. 但是,字符串长度不是预期的5,而是保留默认值。
Replacing oss.width to oss<<std::setw does not work either. oss.width替换为oss<<std::setw也不起作用。 What am I doing wrong? 我究竟做错了什么?

EDIT: 编辑:

The problem appears clearly if the number is of double type say 0.123456789. 如果数字是双精度类型(例如0.123456789),则该问题将清楚显示。

For controlling the number of digits displayed in a floating point number, the function you want is precision , not width . 为了控制浮点数中显示的位数,您需要的功能是precision而不是width If you want to be sure you get the number displayed in fixed notation (rather than scientific) also look at the format flag fixed , used with the setf member function. 如果要确保获得以固定符号显示的数字(而不是科学数字),请查看与setf成员函数一起使用的format标志fixed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM