正在分析具有字符串流精度的浮点值
Parsing float with stringstream - precision?
我使用字符串流来解析字符串中的浮点值。
std::stringstream strs(cp.val);
strs.precision(5);
strs<<std::setprecision(5);
float x; strs>>x;
然而,设置的精度函数似乎不起作用。。有什么方法可以强制解析而不是打印的精度吗?
precision
(以及fixed
和scientific
)只影响输出;输入将解析任何看起来像数值的内容,提取可能是任何数值一部分的所有字符。(这包括十六进制字符,以及整数输入时可能出现的"X"。)如果您想以任何方式限制格式,您必须将其作为字符串读取,验证格式,然后使用std::istringstream
进行转换。
字符串语法不允许解析时的精度,但您可以在解析后设置双倍精度。
例如
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std; //do not use that in real project.
int main()
{
// Initial declarations
stringstream ss("13.321646");
double x = 0.0;
// Parse the double
ss >> x;
// Set the double precision to 2decimals
double roundedX = round(x*100)/100;
// output solution
cout << x << endl;
cout << setprecision(5) << x << endl;
cout << roundedX << endl;
return 0;
}
明显的注意:这是为了降低精度,而不是提高精度。
相关文章:
- 如何在C++中的同一函数中使用字符串和双精度
- C 字符串返回字符串的整数/双精度/长整型值
- 如何从字符串转换为双精度*
- C++如何将字符串逐行转换为双精度
- 如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将双精度值转换为 char 变量时字符串流如何工作
- 在 c++ 中从双精度转换为字符串
- 从字符串转换为双精度和整数 - C++
- 如何从char16_t字符串文字中读取双精度?
- 分析字符串中的双精度和单词
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++将包含非人类可读数据的字符串转换为 200 双精度
- 将大双精度转换为科学记数法以用作字符串?
- 字符串和双精度的麻烦,等值后再得到一个数字
- 如何从字符串流中提取双精度
- 如何调用返回双精度或字符串并将其保存在地图上但作为对象的类的方法
- 在C++中使用atof将带小数的字符串转换为双精度字符串