Change number in a character when reading columns

Viewed 53

I have an input file that looks like:

text
6
    1w    1     3.450   1.324   2.915
    1w    2     3.450   1.324   2.915
    4w    2     3.458   1.379   2.837
    4w    1     3.458   1.379   2.837
    7w    2     3.364   1.345   2.951
    7w    2     3.364   1.345   2.951

and I want the output file to look like:

text
6
    1w    N      3.450   1.324   2.915
    1w    H1     3.450   1.324   2.915
    4w    H2     3.458   1.379   2.837
    4w    N      3.458   1.379   2.837
    7w    H1     3.364   1.345   2.951
    7w    HW2    3.364   1.345   2.951

For the second column, the numbers 1 2 2 1 2 2, I need to print "N" for 1 and "H1" and "H2" for 2 and than again NH1H2, so I mean to tell the program to change once 2 for H1 and then H2. I used

if(p==1)p="N"
if(p==2)p="H1"

but I have no idea how to put do cycle to tell the second 2 is H2 not H1. Can you suggest what to do?

1 Answers

You probably want to keep a running count of the H elements, something like

program p
  implicit none
  
  character(2), allocatable :: element_symbols(:)
  
  character(100) :: text
  integer :: no_elements
  character(2) :: name
  integer :: element_id
  character(2) :: element_symbol
  real :: x,y,z
  
  integer :: h_count
  
  integer :: i,input
  
  ! The elemental symbols, so 1->"N", 2->"H" etc.
  element_symbols = ['N', 'H']
  
  h_count = 0
  
  open(10, file='input.dat')
  open(11, file='output.dat')
  
  read(10,*) text
  write(11,*) text
  read(10,*) no_elements
  write(11,*) no_elements
  
  do i=1,no_elements
    read(10,*) name, element_id, x, y, z
    
    element_symbol = element_symbols(element_id)
    
    if (element_symbol=="N") then
      ! If the element is `N`, reset h_count.
      h_count = 0
    elseif (element_symbol=="H") then
      ! If the element is `H`, update h_count.
      h_count = h_count + 1
      write(element_symbol,'(A,I0)') trim(element_symbol), h_count
    endif
    
    write(11,*) name, element_symbol, x, y, z
  enddo
end program
Related