字符串到浮点转换,支持小数点和小数点逗号(String to floating point conversion with support for both decimal point and decimal comma)
如果我想将两个逗号解释为十进制逗号并将点解释为小数点,如何将字符串转换为浮点数?
该代码解析由我们的客户创建的文本文件。 他们有时使用小数点,有时使用小数点逗号,但不使用千位分隔符。
How do I convert a string to a floating point number if I want both comma interpreted as decimal comma and point interpreted as decimal point?
The code parses text files that have been created by our customers. They sometimes use decimal points and sometimes decimal commas but never thousand separators.
最满意答案
使用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()); }如果你需要处理数千个分隔符,它会更加棘手。
Use std::replace to do the hard work:
#include <cstdlib> #include <string> #include <algorithm> double toDouble(std::string s){ std::replace(s.begin(), s.end(), ',', '.'); return std::atof(s.c_str()); }If you need to cope with thousands separators it'd be much more tricky.
更多推荐
发布评论