从字符串解析小浮点数
C++ parsing small float from string
我希望我的代码从文件中读取参数。文件中有这一行:
tol=1e-10
,我使用atof
将其解析为浮点数:
double tol;
char * c = "1e-10"
tol=atof(c);
但是,它被解析为0
而不是1e-10
。
Edit:事实证明它确实解析正确,很抱歉打扰了你们。我忘了printf
默认不显示小值。我一开始就怀疑这一点,因为我的一张支票冻结了。
代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
double d = atof( "1e-10" );
cout << d << endl;
}
打印1平台以及。
如何打印结果,确保点后面有很多数字。可能是舍入错误
问题是std::atof()
在发生错误时返回0
,因此您无法将两者区分开来。
既然这是一个c++问题,为什么不使用流呢?像这样:
double get_tol(std::istream& is)
{
std::string key;
if( !is>>key || key!="tol" ) throw "You need error handling here!";
char equal;
if( !is>>equal || equal!='=' ) throw "You need error handling here!";
double d;
if( !is>>d )throw "You need error handling here!";
return d;
}
将c
转换为std::string
并使用stringstream
。
相关文章:
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何将时间字符串 (M:SS) 转换为浮点数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++ - 转换标准::浮点数组的字符串
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 将浮点数转换为字符串时如何加快此代码的速度?
- 如何将带有浮点数的字符串转换为十进制?
- 将浮点数向量转换为十六进制/二进制字符串
- 精确且无公差地将浮点数转换为字符串
- 如何创建带有字符串和浮点数的 2D 数组
- 如何使用 c++ 模板实现整数、字符串、浮点数和日期对象的数组
- 解析文本文件中的字符串、整数和浮点数
- 假设浮点数或双 NaN 将始终作为字符串"nan"是否安全?
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 有没有一种简单的方法可以从嵌入的 GNU ARM C++字符串中解析浮点数?
- 将特定格式的字符串拆分为浮点数和字符串
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 将字符串转换为浮点数;无法正确清除字符串流?
- 整数/浮点数/字符串值之间的操作,组合太多