This is my solution for exercise 1-19 of K&R:
Write a function
reverse(s)
that reverses the character strings
. Use it to write a program that reverses its input a line at a time.1
It works, but I'm trying to write good programs. I think the fact that I can't use the length of the vector when already got the line in function getlinea
makes me think I could do better. The function reverse(s)
uses 3 for sentences, which might be a little ugly. I know it doesn't mean it's not good but having to "read" the line 4 times is kind of a little stupid to me. I still can't think of a different solution.
/*
* main.c
*
* Created on: 19/3/2015
* Author: utnso
*/
#include <stdio.h>
#define MAXLINE 1000
void reverse (char s [] );
int getlinea (char s [] , int lim);
int main ()
{
int len;
char palabra [MAXLINE];
while ( ( len = getlinea ( palabra, MAXLINE ) ) >= 0 )
if (len > 0)
printf ("%s\n", palabra);
return 0;
}
int getlinea ( char s [], int lim )
{
int i, c;
i = 0;
while ( ( c = getchar() ) != EOF && c != '\n' && i < lim-1 )
{
s [i] = c ;
++ i;
}
s [i] = '\0';
if ( i > 0 )
reverse ( s ) ;
else
if ( c == EOF )
return -1;
return i ;
}
void reverse ( char turnaround [] )
{
int i, j;
int h = 0;
char aux [MAXLINE];
for ( i = 0; turnaround [i] != '\0' ; ++i )
;
for ( j = i-1 ; j >= 0 ; --j)
{
aux [h] = turnaround [j];
++h;
}
for ( i = 0 ; turnaround [i] != '\0' ; ++i )
turnaround [i] = aux [i];
}
This is the output for
$ ./1-19 < main.c
(it also deletes white lines)
*/ c.niam * * 5102/3/91 :no detaerC * osntu :rohtuA * /* >h.oidts< edulcni# 0001 ENILXAM enifed# ;) ][ s rahc( esrever diov ;)mil tni , ][ s rahc( aenilteg tni )( niam tni { ;nel tni ;]ENILXAM[ arbalap rahc ) 0 => ) ) ENILXAM ,arbalap ( aenilteg = nel ( ( elihw )0 > nel( fi ;)arbalap ,"n\s%"( ftnirp ;0 nruter } ) mil tni ,][ s rahc ( aenilteg tni { ;c ,i tni ;0 = i ) 1-mil < i && 'n\' =! c && FOE =! ) )(rahcteg = c ( ( elihw { ; c = ]i[ s ;i ++ } ) 0 > i ( fi { ;'0\' = ]i[ s ; ) s ( esrever } esle ) FOE == c ( fi ;1- nruter ; i nruter } ) ][ dnuoranrut rahc ( esrever diov { ;j ,i tni ;0 = h tni ;]ENILXAM[ xua rahc ) i++ ; '0\' =! ]i[ dnuoranrut ;0 = i ( rof ; )j-- ; 0 => j ; 1-i = j ( rof { ;]j[ dnuoranrut = ]h[ xua ;h++ } ) i++ ; '0\' =! ]i[ dnuoranrut ; 0 = i ( rof ;]i[ xua = ]i[ dnuoranrut }
1http://cs.indstate.edu/~cbasavaraj/cs559/the_c_programming_language_2.pdf - Page 31