我需要将数据从文件转换为双精度文件,有时数据的格式为:
0.3387000000D+02 0.6067999217D-02
0.5095000000D+01 0.4530799416D-01
0.1159000000D+01 0.2028219738D+00
0.3258000000D+00 0.5039029350D+00
0.1027000000D+00 0.3834209505D+00
您将如何在此处处理D
?
这是一种科学计数法,仅使用D
而不是E
。
我正在考虑在这里使用std::regex
,但希望有一个更优雅的策略。
类似以下内容:
std::regex rr( "((\\+|-)?[[:digit:]]+)(\\.(([[:digit]]+)?))?(d|D)((\\+|-)?)[[:digit:]]+)""?");
答案 0 :(得分:3)
将D
和E
替换为std::replace
,此后很简单:
std::string s = "0.3387000000D+02";
std::replace( s.begin(), s.end(), 'D', 'E');
std::cout << std::stod(s);
或std::replace_if
:
bool isD(char c) {
return c == 'D';
}
std::string s = "0.3387000000D+02";
std::replace_if( s.begin(), s.end(), isD, 'E');
std::cout << std::stod(s);
输出:
33.87
答案 1 :(得分:-1)
您可以这样做。
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
double string2double(std::string s)
{
// Find the index of scientific D
int indexD = s.find('D');
// separate the base from rest, start at 0 and go till index of D, without D
std::string number = s.substr(0, indexD);
//indexD+2 to ignore D and plus
std::string power = s.substr(indexD+2);
// do conversion from string to number
double rawNumber = std::stod(number);
double powerNumber = std::stod(power);
//test
std::cout << rawNumber << std::endl;
std::cout << powerNumber << std::endl;
//return
return rawNumber * std::pow(10, powerNumber);
}
int main()
{
std::string s = "0.3387000000D+02";
std::cout << string2double(s) << std::endl;
return 0;
}