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

2019-09-20 00:44发布

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条回答
来,给爷笑一个
2楼-- · 2019-09-20 01:24

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:

查看更多
登录 后发表回答