C++ 中未读取科学的“d"符号
我需要读取一个数据文件,其中的数字以如下格式写入:
I need to read a data file in which numbers are written in a format like this:
1.0d-05
C++ 似乎无法识别这种科学记数法!关于如何读取/转换这些类型的数字有什么想法吗?
C++ doesn't seem to recognize this type of scientific notation! Any ideas on how I could read/convert those types of numbers?
我需要数字(即 double
/float
)而不是字符串.也许已经有一个类/头来管理这种格式,但我找不到它.
I need numbers (i.e. double
/ float
) not strings. Maybe there is already a class / header to manage this format, but I could not find it.
推荐答案
Fortran 程序生成的文件报告 双精度数(科学计数法) 使用字母 D 而不是 E.
Files produced by Fortran programs report double precision numbers (in scientific notation) using the letter D instead of E.
所以你的选择是:
- 预处理 Fortran 数据文件(一个简单的搜索和替换就足够了).
使用类似:
- Preprocess the Fortran data file (a simple Search and Replace is enough).
Use something like:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::istringstream input("+1.234000D-5 -2.345600D+0 +3.456700D-2");
std::vector<double> result;
std::string s;
while (input >> s)
{
auto e(s.find_first_of("Dd"));
if (e != std::string::npos)
s[e] = 'E';
result.push_back(std::stod(s));
}
for (auto d : result)
std::cout << std::fixed << d << std::endl;
return 0;
}
还有:
- 看看 使用D"读取 ASCII 数字而不是E"使用 C 的科学记数法(它是 C,但你明白了);
- 仔细检查输入文件,因为 Fortran 可以删除E"/D"(请参阅?? 对于三位数指数,Fortran 在输出中删除E" 和 如何在 C++ 中读取 FORTRAN 格式的数字).
- take a look at Reading ASCII numbers using "D" instead of "E" for scientific notation using C (it's C but you get the idea);
- double check the input file since Fortran can drop the 'E' / 'D' (see For three digit exponents Fortran drops the 'E' in the output and How to read FORTRAN formatted numbers in C++).
相关文章