如何修改FORTRAN读取含字符、整数、实数数据的代码使其正常运行?
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.i2reads the integer inside the parentheses (your example uses single-digit numbers with a leading space;i2handles this perfectly, and you can upgrade toi3ori5if you have larger indices later).') = 'matches the fixed characters between the index and the real number, skipping them automatically.f28.18retains 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
ndoesn’t exceed the size of yourxarray (11) to avoid array out-of-bounds errors. - Double-check that
nfileis opened correctly in sequential read mode (the default for most use cases) before running this loop.
内容的提问来源于stack exchange,提问作者Many

