iam*_*ter 0 c++ string floating-point boost
我想将std::string我从csv文件中读取的内容转换为float.有几个浮动表示包括:
0,0728239
6.543.584.399
2,67E-02
Run Code Online (Sandbox Code Playgroud)
这些字符串都应该是浮点数.我首先使用atof(),但转换错误:
2,67E-02 -> 2
6.543.584.399 -> 6.543
Run Code Online (Sandbox Code Playgroud)
然后我使用了boost::lexical_cast<float>(),但是当涉及到包含指数的浮点数时,它会抛出异常
`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
Run Code Online (Sandbox Code Playgroud)
将所有三种类型的字符串转换为浮点数的最佳方法是什么?
http://www.cplusplus.com/reference/clibrary/clocale/
请注意,语言环境配置会影响标准C库中许多函数的行为:在string.h中,函数strcoll和strxfrm受字符转换规则的影响.在ctype.h中,除了isdigit和isxdigit之外的所有函数都受所选扩展字符集的影响.在stdio.h中,格式化的输入/输出操作受字符转换规则和数字格式设置中的小数点字符集的影响.在time.h中,函数strftime受时间格式设置的影响.在此标头中,它会影响其函数setlocale和localeconv返回的值.
http://www.cplusplus.com/reference/clibrary/clocale/setlocale/
setlocale ( LC_NUMERIC, "" ); // "" is the Environment's default locale
Run Code Online (Sandbox Code Playgroud)
然后你可以正确使用atof,scanf等.然而,这是C的做事方式.C++方式是:
float stof(const std::string& input) {
std::stringstream ss;
float result;
static std::locale uselocale("") //again, "" is Environment's default locale
ss.imbue(uselocale);
ss << input;
ss >> result;
return result;
}
Run Code Online (Sandbox Code Playgroud)
所有编译器必须接受这些语言环境:"","C"
MSVC接受这些语言环境:http://msdn.microsoft.com/en-us/library/hzz3tw78.aspx
(等等,MSVC setlocale真的不接受"en_US"吗?)
GCC接受以下语言环境:http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c