如果我希望逗号被解释为十进制逗号,并且点被解释为小数点,我如何将字符串转换为浮点数字?
该代码解析由我们的客户创建的文本文件。他们有时使用小数点,有时使用逗号,但从不使用千位分隔符。
使用std::replace
来做艰苦的工作:
#include <cstdlib>
#include <string>
#include <algorithm>
double toDouble(std::string s){
std::replace(s.begin(), s.end(), ',', '.');
return std::atof(s.c_str());
}
如果你需要处理成千上万的分离器,那就更棘手了。
只需搜索十进制逗号','
并将其转换为'.'
,然后使用<cstdlib>
:中的atof
#include <cstdlib>
#include <cstdio>
#include <string>
double toDouble(std::string s){
// do not use a reference, since we're going to modify this string
// If you do not care about ',' or '.' in your string use a
// reference instead.
size_t found = s.find(",");
if(found != std::string::npos)
s[found]='.'; // Change ',' to '.'
return std::atof(s.c_str());
}
int main(){
std::string aStr("0.012");
std::string bStr("0,012");
double aDbl = toDouble(aStr);
double bDbl = toDouble(bStr);
std::printf("%lf %lfn",aDbl,bDbl);
return 0;
}
如果使用C字符串而不是std::string
,请使用<cstring>
中的strchr
来更改原始字符串(如果以后需要原始版本,请不要忘记将其改回或使用区域设置副本)。
如果您想将其作为std::istream
的正常读取的一部分,您可以创建一个自定义std::num_get<...>
方面,将其放入std::locale
对象中,并使用imbue()
将其安装到流中(或在创建流之前将std::locale
设置为全局区域设置)。