有一个包含行格式的文件:
string,char char integer
我尝试使用以下代码读取和存储在数组中:
module MyModyle
contains
subroutine ReadFileIntoArrays (filename, name_arr, kWh_arr)
implicit none
! function parameters
character (len = *), intent (in) :: filename
character, dimension(:), intent (out) :: name_arr
integer, dimension(:), intent (out) :: kWh_arr
! variables contained on a single line
character (len = 1) :: first_name, second_name
character (len = 20) :: surname
integer :: consumption
integer :: arr_index = 1, ios_status = 0, unit_number = 1
character (len = 30) :: fullname
open (unit = unit_number, file = filename, status = 'old', action = 'read')
do
! read a line from the file
read (unit_number, iostat = ios_status) surname, first_name, second_name, consumption
! check input validity
if (ios_status > 0) then
print *, "Wrong input format!"
print *, surname, first_name, second_name, consumption
exit
else if (ios_status < 0) then ! end of file
print *, "End of file reached."
exit
else ! populate arrays
! concatenate full name
fullname = surname
fullname = fullname//','
fullname = fullname//first_name
fullname = fullname//'.'
fullname = fullname//second_name
fullname = fullname//'.'
name_arr(arr_index) = fullname
kWh_arr(arr_index) = consumption
arr_index = arr_index + 1
end if
end do
close (unit_number)
end subroutine ReadFileIntoArrays
end module MyModule
! --------------------------------------------------------------- !
program MyMain
use MyModule
implicit none
integer, dimension(10) :: consumption
character, dimension(10) :: names
character (11) :: filename = 'clients.txt'
call ReadFileIntoArrays(filename, names, consumption)
end program MyMain
无济于事,我得到的只有:Wrong Input Format!
。
文件阅读有什么问题,怎么做?
注意:经过一项研究,我发现只有简单文件阅读的帖子,主要涉及数字列。