简体   繁体   English

将数字从stringstream转换为具有设定精度的字符串

[英]Convert a number from stringstream to string with a set precision

I would like to obtain a number from stringstream and set it to 5 significant figures. 我想从stringstream获取一个数字并将其设置为5位有效数字。 How do I do this? 我该怎么做呢? So far, this is what I have managed to come up with: 到目前为止,这是我设法提出的:

double a = 34.34566535
std::stringstream precisionValue;
precisionValue.precision(6) << a << std::endl;

However, this is not compiling. 但是,这不是编译。 Thanks. 谢谢。

It doesn't compile because ios_base::precision() returns streamsize (it's an integral type). 它不编译,因为ios_base::precision()返回streamsize (它是一个整数类型)。

You can use stream manipulators : 您可以使用流操纵器

precisionValue << std::setprecision(6) << a << std::endl;

You'll need to include <iomanip> . 您需要包含<iomanip>

std::stringstream::precision() returns a streamsize , not a reference to the stream itself, which is required if you want to sequence << operators. std::stringstream::precision()返回一个streamsize ,而不是对流本身的引用,如果你想对<<运算符进行排序,这是必需的。 This should work: 这应该工作:

double a = 34.34566535;
std::stringstream precisionValue;
precisionValue.precision(6);
precisionValue << a << std::endl;

The precision member function returns current precision, not a reference to the stringstream, so you cannot chain the calls as you've done in the snippet. precision成员函数返回当前精度,而不是对stringstream的引用,因此您不能像在代码段中那样链接调用。

precisionValue.precision(6);      
precisionValue << a;
std::cout << precisionValue.str() << std::endl;

Or use the setprecision IO manipulator to chain the calls: 或者使用setprecision IO操纵器来链接调用:

precisionValue << setprecision(6) << a;
std::cout << precisionValue.str() << std::endl;

You can use std::setprecision from header <iomanip> 您可以从头文件<iomanip>使用std::setprecision <iomanip>

#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

int main()
{
  double a = 34.34566535;
  std::stringstream precisionValue;
  precisionValue << std::setprecision(6);
  precisionValue << a << std::endl;
  std::cout << precisionValue.str();
}

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

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