Indigo
Indigo

Reputation: 3007

Check the input data type and whether it is empty or null

I am asking user to give a value at run time to do some calculations.

  1. I want to test if the user entered value is a real/integer number, and if not then give a warning that the program is expecting a real/integer number here.
  2. In addition, I would as well like to know how do we check if a particular variable at the moment is null or empty. i.e. I have declared a variable but what if at the time of calculation its value is null or empty or not yet set, in that case, the program shouldn't crash instead give a warning to provide a correct value.

Both these operations are much more easier in C++ and C#, but I couldn't find a way to do that in Fortran.

Upvotes: 2

Views: 5413

Answers (2)

tstev
tstev

Reputation: 616

I ran into the same problem where my program requires the user gives input for a missing value. The way I solved it was by having a logical variable (i.e. missing_value_set) initialize to .false.. Then when parsing the command arguments set the logical variable to .true. when the required argument was indeed passed by the user. After parsing the arguments I have a check on that variable.

program main
  logical :: missing_value_set = .false.
  real :: MISS_VALUE = huge(1.0)

  ! Parse arguments
  ...

  if (.not.missing_value_set) then
    write(*, *) "ERROR: --missing argument is required"
    stop
  end if

  ! Rest of program
  ...

end program

No idea if that makes sense - so far it seems to work for me.

Upvotes: 0

M. S. B.
M. S. B.

Reputation: 29401

I guess that "null or empty" you mean whether a variable has been initialized: "not yet set". "null" has a particular meaning for Fortran pointer variables, but I suppose that this is not your question. Fortran doesn't automatically give variables a special value before they are intentionally initialized so there is no easy way to check whether a variable has been initialized. One approach is to initialize the variable its declaration with a special value. That means that you need to know a special value that it will never obtain in the operation of the program. One possibility is to use the huge intrinsic:

program TestVar

   real :: AVar = huge (1.0)

   if ( AVar < huge (1.0) ) then
      write (*, *) "Test 1: Good"
   else
      write (*, *) "Test 1: Bad"
   end if

   AVar = 2.2

   if ( AVar < huge (1.0) ) then
      write (*, *) "Test 2: Good"
   else
      write (*, *) "Test 2: Bad"
   end if

end program TestVar

As warned by @arbautjc, this only works once, even in a subroutine. In a procedure, the initialization with declaration is only done with a first call. Also, if you change the variable type from this example, be sure to understand how huge works (e.g., Long ints in Fortran).

Upvotes: 3

Related Questions