本文介绍了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 thatcouldn''t be parsed. Is there a better way to do this? Trond Valen推荐答案 #include< sstream> #include< string> 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 确实是愚蠢的。但回答你的问题:是的,有更好的方法。 使用来自< 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 insteadof atoi) which can distinguish between zero and an error case. Gavin Deane #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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-23 20:02