You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改FORTRAN读取含字符、整数、实数数据的代码使其正常运行?

How to Modify Fortran Code to Read This Specific File Format?

The Problem

You’ve got a Fortran snippet meant to parse a file with mixed character, integer, and real values, but your current read statement doesn’t align with the actual file format.

Here’s your original code:

real(8), dimension(11), intent(inout) :: x
integer(4) :: idx
character(len=4) :: fake_read_first
character(len=4) :: fake_read_second
integer(4) :: fake_index
do idx = 1_idp, n, 1_idp
    read(nfile, FMT="(a,i5,a,f28.18)") fake_read_first, fake_index, &
        fake_read_second, x(idx) ! read line wise
end do

And your target file lines look like this (spaces preserved):

eps( 1) = -1.534875443410773865
eps( 2) = 1.879729927704710146
eps( 3) = -1.141...

The Fix

The core issue is your format string doesn’t account for the fixed character patterns (eps( and ) = ) in each line. Instead of reading these into dummy character variables, you can directly embed these fixed strings in your format specifier to skip them automatically, focusing only on the values you need: the index and the real number.

Here’s the revised code:

real(8), dimension(11), intent(inout) :: x
integer(4) :: idx
integer(4) :: fake_index
do idx = 1_idp, n, 1_idp
    ! Match the exact fixed structure of each line to read index and real value
    read(nfile, FMT="('eps(', i2, ') = ', f28.18)") fake_index, x(idx)
end do

Why This Works

  • 'eps(' in the format string tells Fortran to expect that exact character sequence at the start of the line—no need for dummy character variables.
  • i2 reads the integer inside the parentheses (your example uses single-digit numbers with a leading space; i2 handles this perfectly, and you can upgrade to i3 or i5 if you have larger indices later).
  • ') = ' matches the fixed characters between the index and the real number, skipping them automatically.
  • f28.18 retains your original high-precision read for the real value, which matches the file’s format exactly.

Extra Tips

  • If your indices might have varying leading spaces or more digits, use a larger integer specifier like i5—Fortran automatically skips leading whitespace for integer reads.
  • Ensure n doesn’t exceed the size of your x array (11) to avoid array out-of-bounds errors.
  • Double-check that nfile is opened correctly in sequential read mode (the default for most use cases) before running this loop.

内容的提问来源于stack exchange,提问作者Many

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:51