C++ 中未读取科学的“d"符号 [英] Scientific `d` notation not read in C++

查看:34
本文介绍了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 程序生成的文件报告 双精度数(科学计数法) 使用字母 D 而不是 E.

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

所以你的选择是:

  1. 预处理 Fortran 数据文件(一个简单的搜索和替换就足够了).
  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天全站免登陆