arrays - 读取输入直到值 < 0
问题描述
任何其他语言都有很多实现,但 Fortran 除外,我无法从中采用。
Sample Input:
5 10 15 20 25 0
Output:
Array: [5, 10, 15, 20, 25]
Sample Input:
5
10
15
20
25
0
Output:
Array: [5, 10, 15, 20, 25]
两种类型的输入都应该有效(单行和多行)。
所以,我尝试的是隐含的 do 循环(因为我确切地知道我最多可以读取 N 个值);但是,如果输入为 0 或任何其他值,我找不到停止阅读的方法。
我已经尝试过的
这段代码显然不会从一行中读取值:
do while (.not.input<0)
read *, input
end do
而这一个不会继续,直到隐含的 do-loop 结束
do while (.not.input<0)
read *, (x(i), i=1, 10)
input = x(i)
end do
解决方案
该程序接受来自标准输入的输入。您可以在以空格分隔的行上放置 1 个以上的整数。该行可以以 0 结尾,例如 10 20 30 0。您也可以每行输入 1 个整数,最后一行为 0。不允许有空行。
program foo
character(len=3) :: fmt = '(A)'
character(len=80) s, t
integer :: m=0
integer, allocatable :: n(:)
allocate(n(0))
do
read(*,fmt) s
5 call get_token(s,t)
if (len_trim(s) == 0 .and. len_trim(t) == 0) goto 30
read(t,*,err=15) i
if (i == 0) goto 20
n = [n,i]
m = m + 1
if (len_trim(s) /= 0) goto 5
end do
15 write(*,fmt) 'conversion issue'
goto 40
30 write(*,fmt) 'blank line'
goto 40
20 if (m == 0) then
write (*,fmt) 'no elements'
goto 40
end if
write(s,'(I0)') m
s = '(' // trim(s) // '(I0,1X))'
write(*,s) n
40 if (allocated(n)) deallocate(n)
contains
subroutine get_token(str, token)
character(len=*), intent(inout) :: str
character(len=*), intent(out) :: token
j = scan(trim(str), ' ');
if (j /= 0) then
token = str(1:j)
str = adjustl(str(j:len_trim(str)))
else
token = trim(str)
str = ''
end if
end subroutine get_token
end program foo
可能有一两个错误。啊,有一个错误!没有什么比最后一分钟的小改变更能将扳手扔进混合物中了。
推荐阅读
- c - 在 C 中,为什么不能使用 sscanf() 修剪字符串?
- sql - 如果过程成功,过程返回真或假 PL/SQL
- mysql - Xampp MySQL 意外关闭(问题不在于端口)
- jquery - jQuery在特殊字符后将文本换行
- mongodb - MongoDB 集合字段与当前日期比较以获取一天内的活跃用户数
- r - 如何在数据框中创建具有另一个值的列
- javascript - 子进程执行失败的电子应用程序调用 nodejs SpeedTest
- java - 将依赖的 jar 移动到工作节点
- c++ - 在 c++ 中使用“transform”会给出一个错误,即 this 没有在范围内声明
- azure - 关于azure的formrecognizer功能的问题