读取内容取决于第一个字符的行 [英] Reading a line whose contents depends on the first character

查看:162
本文介绍了读取内容取决于第一个字符的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fortran中,实际的阅读方式是:

  A 1. 2. 3. 

如果第一个字符是A,但不读取:

  Z 

如果第一个字符是一个Z的例子。



如果我尝试读整行:

  read(1,*)char,number1,number2,number3 

然后如果数字缺失,则会发生错误。因此,我需要一种方式来读取该行上的A,并根据A或Z读取,如果需要,请阅读。

>解决方案

您可以随时阅读标志并在iolist中使用表达式来确定是否要读取更多内容。

az.f90:

 程序az 
隐式无
实数1,数字2,数字3
字符azflag
整数iunit
integer i
open(newunit = iunit,file ='az.txt',status ='old')
do
number1 = -1
number2 = -1
number3 = -1
read(iunit,*,end = 10)azflag,(number1,number2,number3&
,i = 1,merge(1,0,any(azflag == ['A','a'])))
if(any(azflag == ['A','a']))then
write(*,*)'numbers read !'
else
write(*,*)'nothing read'
end if
write(*,*)number1,number2,number3
end do
10继续
结束程序az

az.txt:

  A 1. 2. 3. 
Z
a 4. 5. 6.
z

输出:

 数字已读! 
1.000000 2.000000 3.000000
没有读取
-1.000000 -1.000000 -1.000000
数字读取!
4.000000 5.000000 6.000000
无读数
-1.000000 -1.000000 -1.000000


In Fortran, what would be the practical way to read:

 A 1. 2. 3.   

if the first character is an "A", but to not read the:

 Z

rest if the first character is a "Z" for example.

If I try to read the line at whole:

read(1,*)char, number1, number2, number3

then an error will occur if the numbers are missing. So I need a way to read an "A" stay on that line, and depending on the "A" or a "Z" read, if needed the rest.

解决方案

You can always read the flag and use an expression in the iolist to determine whether you want to read any more stuff.
az.f90:

program az
   implicit none
   real number1, number2, number3
   character azflag
   integer iunit
   integer i
   open(newunit=iunit,file='az.txt',status='old')
   do
      number1 = -1
      number2 = -1
      number3 = -1
      read(iunit,*,end=10) azflag, (number1,number2,number3 &
         ,i=1,merge(1,0,any(azflag==['A','a'])))
      if(any(azflag==['A','a'])) then
         write(*,*) 'numbers read!'
      else
         write(*,*) 'nothing read'
      end if
      write(*,*) number1, number2, number3
   end do
10 continue
end program az

az.txt:

 A 1. 2. 3.
 Z
 a 4. 5. 6.
 z

Output:

 numbers read!
   1.000000       2.000000       3.000000
 nothing read
  -1.000000      -1.000000      -1.000000
 numbers read!
   4.000000       5.000000       6.000000
 nothing read
  -1.000000      -1.000000      -1.000000

这篇关于读取内容取决于第一个字符的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆