使用FORTRAN阅读和打印

时间:2013-01-04 19:04:26

标签: function fortran gfortran fortran95

我需要编写一个可以读取和打印.dat文件的Fortran程序。

(文件homework_6.dat包含书籍记录:名称(最多25个字符),发布年份(4位整数),价格(6位真实),ISBN(13位整数)。编写程序读取文件(homework_6.dat)并按以下格式打印(在屏幕上或在另一个文件中)详细信息:

                                     Publish   
          Name                        Year    ($)        ISBN
       -------------------------      ----   ------     -------------
       Principles of Combustion       2005    107.61     9780471046899
       An Introduction to Comb        2011    193.99     9780073380193 
       Guide to Fortran               2009     71.95     9781848825420
       Modern Fortran Explain         2011    100.00     9780199601417
       Introduction to Program        2012    200.00     9780857292322)

我写的是

program dat
implicit none
character (len=25) :: Name
integer :: i, publish_year, ISBN
real :: price 
open(unit=7, file="homework_6.dat", status="old", action="readwrite")
do i=1, 10
read (unit=7,fmt="(a25,i4,f3.2,i13)") Name, publish_year, price, ISBN
write (unit=7,fmt="(a25,i4,f3.2,i13)") Name, publish_year, price, ISBN
end do
close(unit=7)
end program dat

但Fortran说第8行有错误

我不知道该怎么做:(

Sonya(ITU)

- 编辑 -

所以我试着写一个程序,但执行后仍然有错误

program dat
    implicit none
    character (len=25) :: Name
    character (len=13) :: ISBN
    integer :: i, publish_year
    real :: price 
    open(unit=10, file="homework_6.dat", status="old", action="readwrite")
    open(unit=11, file="output_hw6.dat")
    !Comment: these below 3 lines are for skipping 3 heading your input
    read(10,*)
    read(10,*)
    read(10,*)
    do i=1, 10
    read (10,*) Name, publish_year, price, ISBN
    write (11,1) Name, publish_year, price, ISBN
    1 format(a25,2x,i4,2x,f3.2,2x,a13)
    end do
    close(unit=10)
    end program dat

我在第14行有一个错误。 错误52,字段中的字符无效  DAT - 在第14行的文件homework.f95中[+ 01b3]

2 个答案:

答案 0 :(得分:1)

您正在使用列表定向格式阅读,但这不起作用。书名中有空格,编译器无法找到,结束的地方以及年份的开始位置。

您必须使用格式。提示:在read语句中使用格式字符串,而不是带有标签的格式语句。格式与您输出的格式类似。

另一个提示,您的价格输出格式太短。我推荐f6.2。

答案 1 :(得分:0)

在第8行中将unit = 7替换为7.但问题是您正在从homework_6.dat读取并在同一文件中写入。您可以在屏幕上打开新文件或输出。我已修改您的代码,以便从数据文件中读取,假设它在数据前有3行标题。

    program dat
    implicit none
    character (len=25) :: Name
    integer :: i, publish_year, ISBN
    real :: price 
    open(unit=7, file="homework_6.dat", status="old", action="readwrite")
    open(unit=8, file="output_hw6.dat")
    !Comment: these below 3 lines are for skipping 3 heading your input                 
    read(7,*)
    read(7,*)
    read(7,*)
    do i=1, 10
    read (7,*) Name, publish_year, price, ISBN
    write (8,1) Name, publish_year, price, ISBN
    1 format(a25,2x,i4,2x,f3.2,2x,i13)
    end do
    close(unit=7)
    end program dat

通过咨询任何初学者fortran书,可以轻松解决您的问题。