Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Mix variable type in fortram

pfwang
Beginner
2,036 Views

How can I mix two variables with different types in fortran. I intend to have a fixed name (character) such as Name1 = "File". Another variable, Number, will be defined as a variable (character) which may change by model input or within the code. For example, Number may begivenas"1", "2", or "1001","3001".Then I need to combine Name1 and Number so that the newvariable (Name2)is named as "File1", or "File2", or "File1001", or "Filr3001", which are obtained by adding Name1 ("File") and Number ("1", :2", "1001", or "3001").

Do you know how to do it?

0 Kudos
6 Replies
Steven_L_Intel1
Employee
2,036 Views
It is not completely clear to me what you want to do.

Do you want to create a character variable whose value consists of a fixed prefix and a variable suffix? If so, then you use the "internal write" feature to do that, for example:

character(10) name
write (name,'(A,I0)') 'File', 1001

When run, this assigns the value 'File1001' to variable "name".

If you actually want to create a Fortran variable this way, so that the name of the variable changes at run-time, no, you can't do that.
0 Kudos
jimdempseyatthecove
Honored Contributor III
2,036 Views

Consider using the '//' operator

character(10) name
character(4)Anumber
integer number

number = 1234! pick up integer number

write(Anumber,100) number
100 format(I0)
name ='File'//Anumber
...
Anumber = ':2'
name ='File'//Anumber
...

Jim Dempsey

0 Kudos
pfwang
Beginner
2,036 Views

Thanks, Jim. Your example work well if the input (number) is an integer. What if my input is characters or strings (such as, ":Case #1", or ":Case #A100"), which is Anumber in your example, which will be input from screen by the users? In other words, I hope to have the following:

name=File:Case #1 ; or

name=File:Case #100

Any more ideas?

0 Kudos
Steven_L_Intel1
Employee
2,036 Views
The use of "internal write" as in my example (and part of Jim's) gives you extraordinary flexibility for how you construct strings. You can use any of the formatting you would use to write to a file. If you want to include strings, use the A format.
0 Kudos
jdchambless
Beginner
2,036 Views
Hi Steve,
Would you mind letting me know where to find the formatting flags that you put in the quotes in your WRITE statement? (e.g. the '(A,I0)' part of "write (name,'(A,I0)') 'File', 1001")
Thanks,
Jason C.
0 Kudos
Steven_L_Intel1
Employee
2,036 Views
That's a standard Fortran format - look at the documentation for "I/O Formatting" in the Intel Fortran Language Reference. The Fortran language allows you to put a format as a character constant (or variable!) in place of a FORMAT label in an I/O statement. Anything valid in a FORMAT can go here. Don't forget the parentheses at each end, as they're required.
0 Kudos
Reply