在C ++中无法读取科学的d表示法 [英] Scientific `d` notation not read in C++

查看:143
本文介绍了在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程序生成的文件报告双精度数字(以科学计数法表示)使用

Files produced by Fortran programs report double precision numbers (in scientific notation) using the letter D instead of E.

所以您的选择是:


  1. 预处理Fortran数据文件(一个简单的 Search and Replace 就足够了)。

  2. 使用类似以下内容的东西:

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


也:

  • 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++).

这篇关于在C ++中无法读取科学的d表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆