! This file: http://ftp.aset.psu.edu/pub/ger/fortran/hdk/CountCols.f90 ! Program CountCols ! Given an input text file of space separated number data (of same type ! to make it simple), can you think of an elegant way to extract number ! of columns in a given row? (using pure Fortran, of course) ! - each EOL starts a new row ! - every column is separated by at least one space -- can be more ! Problem posed by slyi.ath.cx, comp.lang.fortran 28 July 2005. ! This solution by David Frank. character (Len=101) :: Line integer :: NumLine ! Create sample file, CountCols.txt open (9,file="CountCols.txt") write (9,"(a)") "11 222 0 333 44444" write (9,"(a)") " 55 666 777, 888888 999 123" rewind (9) ! ! Count the number of (numeric) columns of data. NumLine = 0 print *, "Results should be Column Counts: 5 and 6." do Read(9,"(A)",End=99) Line NumLine = NumLine + 1 print *, CountWords(Line) end do 99 print *, "All Done. ",NumLine," lines processed." contains Function CountWords(Line) result (NumWords) ! CountWords counts the number of words in (untrimmed) line. Character (*) :: Line Integer :: NumWords, i NumWords = 0 do i = 1,Len(Line)-1 if (line(i:i) /= " ".and.line(i+1:i+1) == " ") then NumWords = Numwords + 1 endif end do End Function CountWords End Program CountCols