Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read data with name and value from txt in fortran separated by commas

Status
Not open for further replies.

Dvocvet

Technical User
Dec 3, 2011
2
SK
Hi everybody

I need to read some data from txt file in format for example like these:

a=150,b=300,c=500

Then I will use that data for further calculating. For example:

x=a+b+c

Is that possible in Fortran? Is there some command or format for READ command?
Please help!
 
The general way to do that consists in :

- reading the entire line as a text,

- looking for the character "," to tokenize that text,

- looking for the character = to separate the name and the value in each token

- reading the value in each token

But it exists also easier possibilities if you accept to modify a little bit the form of the data like. For instance, the use of a namelist :

Code:
program t59
  implicit none
  double precision :: a,b,c,y
  namelist/list/a,b,c
  read(*,list)
  y=a+b+c
  write(*,*) y
end program

The data become :

Code:
&list
a=150,b=300,c=500
/

Here is the result :

Code:
[lcoul@localhost test]$ ifort t59.f90
[lcoul@localhost test]$ ./a.out < d
   950.000000000000

Notice that a namelist is very flexible :

- it is possible to initialize the variables in the source file before reading the namelist and to provide, in the data, only few changes.

- it is possible to include in a namelist many kinds of variables like arrays, derived type and even allocatable variables.

- an array in a namelist may be initialized globally or element by element



François Jacq
 
Thanks people.

I solved problem on the next way:

program prog

implicit none
double precision::kapa,r2,T2,a2

open (1,file='list.txt')
read (1,*) (kapa,r2,T2)


a2=sqrt(kapa*r2*T2)

print *, "a2=",a2
end program prog

Where input data in list.txt look like these:

1.4,280,333

So, input data are without name of data and '='.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top