I would like to use deferred-length character strings in a \"simple\" manner to read user input. The reason that I want to do this is that I do not want to have to declare t
Deferred length arrays are just that: deferred length. You still need to allocate the size of the array using the allocate
statement before you can assign values to it. Once you allocate it, you can't change the size of the array unless you deallocate
and then reallocate
with a new size. That's why you're getting a debug error.
Fortran does not provide a way to dynamically resize character arrays like the std::string
class does in C++, for example. In C++, you could initialize std::string var = "temp"
, then redefine it to var = "temporary"
without any extra work, and this would be valid. This is only possible because the resizing is done behind the scenes by the functions in the std::string
class (it doubles the size if the buffer limit is exceeded, which is functionally equivalent to reallocate
ing with a 2x bigger array).
Practically speaking, the easiest way I've found when dealing with strings in Fortran is to allocate a reasonably large character array that will fit most expected inputs. If the size of the input exceeds the buffer, then simply increase the size of your array by reallocate
ing with a larger size. Removing trailing white space can be done using trim
.