【问题标题】:Scientific `d` notation not read in C++ [closed]C ++中未读取科学的`d`符号[关闭]
【发布时间】:2014-07-02 09:07:40
【问题描述】:

我需要读取一个数据文件,其中的数字以如下格式写入:

1.0d-05

C++ 似乎无法识别这种科学记数法!关于如何读取/转换这些类型的数字有什么想法吗?

我需要数字(即double / float)而不是字符串。也许已经有一个类/头来管理这种格式,但我找不到它。

【问题讨论】:

  • 编写自己的解析器?
  • C 预处理器甚至不打算这样做?!?
  • 或者只是将d 替换为e...
  • 是 1.0d-05 和 1.0e-05 一样吗?
  • 如果可以选择修复 fortan,您可以轻松更改为旧的 E 格式

标签: c++ fortran scientific-notation data-files


【解决方案1】:

Fortran 程序生成的文件使用字母 D 而不是 E 报告 double precision numbers (in scientific notation)

所以你的选择是:

  1. 预处理 Fortran 数据文件(一个简单的搜索和替换就足够了)。
  2. 使用类似的东西:

    #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;
    }
    

还有:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多