字符串到浮点的转换,同时支持小数点和小数逗号
String to floating point conversion with support for both decimal point and decimal comma
如果我希望逗号被解释为十进制逗号,并且点被解释为小数点,我如何将字符串转换为浮点数字?
该代码解析由我们的客户创建的文本文件。他们有时使用小数点,有时使用逗号,但从不使用千位分隔符。
使用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
设置为全局区域设置)。
相关文章:
- 编译时未启用intel oneApi CUDA支持
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用CMake检测支持的C++标准
- 为什么istream不支持右值提取
- 当我编译webrtc服务器时,Windows上只支持clang-cl
- 扩展光电二极管探测器以支持多个传感器
- MSVC是否支持C++11样式的属性而不是__declspec
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 用c++把小数点转换成八进制
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 使用 cin 时接受小数点后的 2 位数字
- 哪个C++规范开始支持 std::vector
- 如何检测VS C++编译器是否支持C++11?
- CertGetCertificateChain 具有支持的内存存储和证书信任列表
- Casablanca/cpprestsdk listener.support接受函数,但不支持方法
- 将 IPv6 支持添加到雨量计
- 为什么C++不支持对未初始化变量进行智能分析?
- 字符串到浮点的转换,同时支持小数点和小数逗号