Float-to-string转换引发异常而不是像atof那样返回0.0 [英] Float-to-string conversion that raises exception instead of returning0.0 like atof

查看:135
本文介绍了Float-to-string转换引发异常而不是像atof那样返回0.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!


愚蠢的atof,当它试图解析类似

" fish"之类的东西时返回0.0。所以我不知道这个数字是真的是0还是一个字符串

无法解析。还有更好的办法吗?


Trond Valen

Hi!

Stupid atof, it returns 0.0 when it tries to parse something like
"fish". So I don''t know whether the number was really 0 or a string that
couldn''t be parsed. Is there a better way to do this?

Trond Valen

推荐答案

Trond Valen写道:
Trond Valen wrote:
嗨!

愚蠢的atof,它在尝试解析类似
fish的东西时返回0.0。所以我不知道这个数字是真的是0还是一个无法解析的字符串。有更好的方法吗?
Hi!

Stupid atof, it returns 0.0 when it tries to parse something like
"fish". So I don''t know whether the number was really 0 or a string that
couldn''t be parsed. Is there a better way to do this?




#include< sstream>

#include< string>
< br $>
class bad_float {};


float string_to_float(const std :: string& s)

{

std :: istringstream iss(s);

浮动f;

iss>> f;


if(!iss)throw bad_float();


return f;

}

Jonathan



# include <sstream>
# include <string>

class bad_float {};

float string_to_float(const std::string &s)
{
std::istringstream iss(s);
float f;
iss >> f;

if (!iss) throw bad_float();

return f;
}
Jonathan




Trond Valen写道:

Trond Valen wrote:
嗨!

愚蠢的atof,它在尝试解析类似
fish的东西时返回0.0。所以我不知道这个数字是真的是0还是一个无法解析的字符串。有更好的方法吗?
Hi!

Stupid atof, it returns 0.0 when it tries to parse something like
"fish". So I don''t know whether the number was really 0 or a string that
couldn''t be parsed. Is there a better way to do this?




确实是愚蠢的。但回答你的问题:是的,有更好的方法。

使用来自< sstream>的C ++字符串流或使用strtod(和strtol代替

of atoi)可以区分零和错误情况。


Gavin Deane



Stupid indeed. But to answer your question: yes, there is a better way.
Use C++ stringstreams from <sstream> or use strtod (and strtol instead
of atoi) which can distinguish between zero and an error case.

Gavin Deane


Jonathan Mcdougall写道:
Jonathan Mcdougall wrote:
Trond Valen写道:
Trond Valen wrote:
嗨!

愚蠢atof,当它试图解析类似
fish的东西时,它返回0.0。所以我不知道这个数字是真的是0还是一个无法解析的字符串。有没有更好的方法呢?
Hi!

Stupid atof, it returns 0.0 when it tries to parse something like
"fish". So I don''t know whether the number was really 0 or a string that
couldn''t be parsed. Is there a better way to do this?



#include< sstream>
#include< string>

class bad_float {};

float string_to_float(const std :: string& s)
{st / :: istringstream iss(s);
float f;
iss >> f;

if(!iss)throw bad_float();

返回f;
}

Jonathan


# include <sstream>
# include <string>

class bad_float {};

float string_to_float(const std::string &s)
{
std::istringstream iss(s);
float f;
iss >> f;

if (!iss) throw bad_float();

return f;
}
Jonathan




谢谢:)



Thanks :)


这篇关于Float-to-string转换引发异常而不是像atof那样返回0.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆