Scientific `d` notation not read in C++ [closed]

纵饮孤独 提交于 2019-12-16 18:08:15

问题


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:

  1. Preprocess the Fortran data file (a simple Search and Replace is enough).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!