问题
I need to read a data file in which numbers are written in a format like this:
1.0d-05
C++ doesn't seem to recognize this type of scientific notation! Any ideas on how I could read/convert those types of numbers?
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.
回答1:
Files produced by Fortran programs report double precision numbers (in scientific notation) using the letter D instead of E.
So your options are:
- 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; }
Also:
- 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++).
来源:https://stackoverflow.com/questions/24527075/scientific-d-notation-not-read-in-c