Santhucool
Santhucool

Reputation: 1726

Pass arguments and take sum

I am passing two values to my Fortran program, I need to get the sum of those arguments and print it as result:

I have the program for reading arguments as follows:

PROGRAM Argtest

  IMPLICIT NONE
  integer*4 nargs,i
  character arg*80 

nargs = iargc() 

do i = 0,nargs 
  call getarg(i, arg) 
  print '(a)', arg
end do
END 

I am passing the values 10 and 20. I tried like this:

PROGRAM Argtest

  IMPLICIT NONE
  integer:: nargs,i
  character:: arg
  integer:: num1
  integer:: num2
  integer:: result

nargs = iargc() 

do i = 1,nargs 
  call getarg(i, arg) 
  !print *, arg
  IF( i == 1) THEN
   num1 = ichar(arg)
  ELSE IF(i == 2) THEN
      num2  = ichar(arg)
  ELSE

  end IF
end do
result = num1+num2
print *, num1
print*,num2
END

I need to print the answer as 30. But I am getting values 49 and 50 instead of getting 10 and 30. Please help me.

Upvotes: 0

Views: 92

Answers (1)

chw21
chw21

Reputation: 8140

Here is a very simple version: It reads the arguments as strings, converts them into ints one after the other, and adds them all up.

PROGRAM Argtest

  IMPLICIT NONE
  integer*4 nargs,i
  character arg*80
  integer :: total, int_arg

nargs = iargc()

total = 0

do i = 1,nargs
  call getarg(i, arg)
  read(arg, *) int_arg
  total = total + int_arg
end do

print *, "total is ", total

END

Note that I am starting from argument 1, not 0 (as that is your program name, and can't be converted into a number).

You have now updated your question: ichar converts a single character into the integer that corresponds to that character's ASCII code. You need to use read(ch_num, '(I)') int_num to convert a string like "10" to the integer number 10.

Upvotes: 1

Related Questions