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

How can you write an array of digits to a string?

MFerguson
Beginner
393 Views

I have two variables defined like so:

 

character(10) :: str = "1402356789"

integer, dimension(10) :: numbers = (/ 1,4,0,2,3,5,6,7,8,9 /)

 

And I am trying to write the array numbers into the string str.

I set str to blank and then try to reassign the digits from numbers, but it causes an error termination.

 

str = ""
write(str,*) numbers

Obviously the write statement does not work with input of arrays, how can I do this using some other method? Is the correct way to write each digit to the end of the string somehow?

 

 

 

 

0 Kudos
1 Solution
mecej4
Black Belt
379 Views

When you want tight control over output, such as writing a single digit for each number with no intervening spaces, you have to write your own format specification. For instance:

program digits
character(10) str
integer :: nums(10) = (/ 1,4,0,2,3,5,6,7,8,9 /), i
write(str,'(10i1)')nums
print '(A)',str
end program

View solution in original post

4 Replies
mecej4
Black Belt
380 Views

When you want tight control over output, such as writing a single digit for each number with no intervening spaces, you have to write your own format specification. For instance:

program digits
character(10) str
integer :: nums(10) = (/ 1,4,0,2,3,5,6,7,8,9 /), i
write(str,'(10i1)')nums
print '(A)',str
end program
JohnNichols
Valued Contributor II
310 Views

There are a lot of posts on this forum about that problem, I suggest for a broader offering you do a search for the more general solution, although mecej4,  has answered your question.  The code is often provided. 

jimdempseyatthecove
Black Belt
368 Views

Also, note that mecej4 has specified the length of the string for the write to use.

WRITE writes in place into the specified buffer.  It does not write to a temporary (of necessary size) then perform a realloc lhs with "=".

If the end result length is unknown, you can write to an overly large temporary of your own, then use YourVar=TRIM(YourTemporary)

 

Jim Dempsey

mecej4
Black Belt
322 Views

MFerguson wrote: "Obviously the write statement does not work with input of arrays"

 

That's a hasty conclusion. The reason that the WRITE failed is that the the output buffer was not of sufficient size to contain the output, and the error message makes this clear:

forrtl: severe (66): output statement overflows record, unit -5, file Internal List-Directed Write

The format used with list-directed output is compiler specific; with Intel Fortran, each output integer consumes 12 characters, so the variable str would need to be at least 120 characters long to hold the output, and that length, 120, is specific to this version of Ifort.

Reply