Richard Fitzhugh
Richard Fitzhugh

Reputation: 422

Variable length strings in fortran

So I'm just getting started learning Fortran because apparently it's still used for a lot of scientific computing. One of the things that I already hate about it is that compared to C++, strings are a nightmare. At the moment, I'm just trying to find a simple way to read in a string provided by the user and then spit it back out without all the trailing whitespace.

Here's the code I have right now, which according to what I've read should work under later Fortran standards, i.e. 2003/2008 (though I could easily have made errors of which I'm unaware). I'm trying to compile it on the MinGW version of gfortran that came with Code::Blocks 13.12.

program tstring
implicit none
character(100) io_name
character(len=:), allocatable :: final_name

print *, "What is your name, O master?"
read *, io_name
final_name = trim(io_name)

print *, "Excellent, master ", final_name, "!"
end program

It compiles just fine, but still has a massive amount of whitespace between final_name and the "!". The whitespace is somewhat dependent on the number of characters I give to io_name, but not in a particularly logical manner (15 characters gives more whitespace than 30, for example). Particularly bewildering to me is that if I give certain numbers of characters to io_name (between about 17 and 22) then instead of printing out the name, the program runs into a segfault.

Perhaps the most difficult part of this for me is that good Fortran documentation is very hard to find, especially for the 2003 and later standards. So if anybody could point me to some good documentation, I'd really appreciate it!

Upvotes: 2

Views: 1812

Answers (1)

Get a more recent compiler. Gfortran 4.8 (AFAIK the oldest supported version) should work just fine with your code.

Strings are not really any nightmare, just stop thinking in C++ and trying to translate that in Fortran. It is quite possible to write tokenizers, parsers and DSL interpreters in Fortran.

Regarding the resources, it is off-topic here and there are numerous books and tutorials out there. Search for Fortran Resources at http://fortranwiki.org/fortran/show/HomePage

Upvotes: 4

Related Questions