NOT Educating FORTRAN programmers to use C

Daniel R. Levy levy at cbnewsc.ATT.COM
Sun Jan 21 08:55:01 AEST 1990


> > You write character manipulation programs in Fortran?
> 
> Why not?  It's as fast as the fastest mechanism C has for Characters
> (or should be), it has built-in concatenate and substring syntax
> (instead of C's clumsy looking function calls for these features),
> and it's widely regarded as something that Fortran did (nearly)
> right - even by people who otherwise don't like Fortran.

Well... depends on what you're doing with the strings.  Fortran uses the
convention that character strings are right-padded with blanks (for things
like READ with a-format where the input buffer is longer than the input record
[strictly speaking, isn't this really a nonstandard but common extension to
accommodate variable size input records?], the INQUIRE statement, and assigning
one string to another).  This means juggling the length information along with
the strings (nothing stops you from doing that in C B.T.W.) and/or having a
function analogous to C's "strlen" to give you the length of a blank-padded
string.  You can't concatenate or print a "zero length" string -- that
must be special-cased.  And, of course, information about trailing blanks in
input records is lost.  E.g.:

C
C  FORTRAN77 code to read two lines (assumed 80-characters wide, max),
C  put their concatention in a buffer,
C  then print the concatenation between double quotes
C
	CHARACTER*80 STR1, STR2
	CHARACTER*160 STR3
	READ(5,10) STR1
	READ(5,10) STR2
10	FORMAT(A)
	LSTR1=LENGTH(STR1)
	LSTR2=LENGTH(STR2)
	IF (LSTR1.EQ.0) THEN
		STR3=STR2
		LSTR3=LSTR2
	ELSE IF (LSTR2.EQ.0) THEN
		STR3=STR1
		LSTR3=LSTR1
	ELSE
		STR3=STR1(1:LSTR1)//STR2(1:LSTR2)
		LSTR3=LSTR1+LSTR2
	ENDIF
	IF (LSTR3.EQ.0) THEN
		WRITE(6,20)
20		FORMAT(1X,'""')
	ELSE
		WRITE(6,30)STR3(1:LSTR3)
30		FORMAT(1X,A)
	ENDIF
	STOP
	END

	FUNCTION LENGTH(STRING)
	CHARACTER*(*) STRING
	DO 10 LENGTH=LEN(STRING),1,-1
10	IF (STRING(LENGTH:LENGTH).NE.' ') RETURN
	LENGTH=0
	RETURN
	END

Ugh.  Now let's try that in C...

#include <stdio.h>
main()
{
	char str1[81];
	char str2[81];
	char str3[161];
	void exit();

	(void) gets(str1);
	(void) gets(str2);
	(void) sprintf(str3,"%s%s",str1,str2);
	(void) printf("\"%s\"\n",str3);
	exit(0);
}
	
'Nuff said.
-- 
Daniel R. Levy                     >>> God: just say "yes" <<<
AT&T Bell Laboratories     UNIX(R) mail:  att!ttbcad!levy, att!cbnewsc!levy
5555 West Touhy Avenue     Any opinions expressed in the message above are
Skokie, Illinois  60077    mine, and not necessarily AT&T's.



More information about the Comp.lang.c mailing list