在 c++ 中将字符串转换为浮点数
我想将从 csv 文件读取的 std::string
转换为 float
。其中包含几种浮点表示形式,例如:
0,0728239
6.543.584.399
2,67E-02
这些字符串都应该是浮点。首先我使用了atof()
,但是转换错误:
2,67E-02 -> 2
6.543.584.399 -> 6.543
然后我使用了boost::lexical_cast
,但是当涉及到带有指数的浮点数时包括在内,它会引发以下异常
`terminate` called after throwing an instance of
`'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'`
`what()`: bad lexical cast: source type value could not be interpreted as target
Aborted
将所有三种类型的字符串转换为浮点数的最佳方法是什么?
I want to convert a std::string
which I read from a csv file to a float
. There are several float representations included like:
0,0728239
6.543.584.399
2,67E-02
These string should all be floats. First I used atof()
, but the conversion was wrong:
2,67E-02 -> 2
6.543.584.399 -> 6.543
Then I used boost::lexical_cast<float>()
, but when it comes to a float with an exponent included, it throws following exception
`terminate` called after throwing an instance of
`'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'`
`what()`: bad lexical cast: source type value could not be interpreted as target
Aborted
What is the best way to get all three types of strings converted to a float?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
scanf
设置了正确的区域设置。严重地。在这种情况下,可以省去用“c++ 方式”进行操作的麻烦。scanf
with the correct locale set. Seriously. Save yourself the hassle of doing it the "c++ way" in this case.http://www.cplusplus.com/reference/clibrary/clocale/
http://www.cplusplus.com/reference/clibrary/clocale/setlocale/
然后就可以正确使用atof、scanf等了。然而,这就是 C 的做事方式。 C++ 方式是:
所有编译器都必须接受这些语言环境:“”、“C”
MSVC 接受以下区域设置: http://msdn.microsoft.com/en-us/库/hzz3tw78.aspx
(等等,MSVC
setlocale
真的不接受“en_US”吗?)GCC 接受以下语言环境:http://gcc.gnu。 org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c
http://www.cplusplus.com/reference/clibrary/clocale/
http://www.cplusplus.com/reference/clibrary/clocale/setlocale/
Then you can use atof, scanf, etc correctly. However, that's the C way of doing things. The C++ way is:
All compilers must accept these locales: "", "C"
MSVC accepts these locales: http://msdn.microsoft.com/en-us/library/hzz3tw78.aspx
(wait, does MSVC
setlocale
really not accept "en_US"?)GCC accepts these locales: http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c
应该这样做:
在 coliru 上实时查看
This should do :
See it live on coliru