home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Usenet 1994 October
/
usenetsourcesnewsgroupsinfomagicoctober1994disk1.iso
/
altsrc
/
articles
/
10059
< prev
next >
Wrap
Text File
|
1994-06-19
|
3KB
|
107 lines
Path: wupost!cs.utexas.edu!swrinde!sgiblab!cs.uoregon.edu!reuter.cse.ogi.edu!netnews.nwnet.net!news.u.washington.edu!dbrick
From: dbrick@u.washington.edu (Douglas Brick)
Newsgroups: alt.sources,comp.sources.misc,comp.lang.c
Subject: Beginning C Silliness (reverses text)
Date: 25 Mar 1994 03:15:27 GMT
Organization: University of Washington
Lines: 94
Approved: No!
Message-ID: <2mtl0f$512@news.u.washington.edu>
NNTP-Posting-Host: stein.u.washington.edu
Xref: wupost alt.sources:10059 comp.sources.misc:4572 comp.lang.c:79445
I've been trying to teach myself C by working through Kernighan and
Ritchie's 2nd ed. of The C Programming Language, and couldn't resist
posting my solution to ex. 1-19. If you run text through it, it will
reverse the text across the screen, like this:
dna nahginreK hguorht gnikrow yb C flesym hcaet ot gniyrt neeb ev'I
tsiser t'ndluoc dna ,egaugnaL gnimmargorP C ehT fo .de dn2 s'eihctiR
lliw ti ,ti hguorht txet nur uoy fI .91-1 .xe ot noitulos ym gnitsop
:siht ekil ,neercs eht ssorca txet eht esrever
--
#include <stdio.h>
#define MAXLINE 79 /* screenwidth - 1 */
reverse(); /* reverses the character string 's' */
int getline(); /* reads a line of input into an array */
copy(); /* copies one array into another */
elimws(); /* eliminates trailing whitespace */
/* bkwds: prints reversed text lines */
main()
{
int i;
int len; /* current line length */
char line[MAXLINE+1]; /* current input line */
while ((len = getline(line, MAXLINE+1)) > 0){ /* as long as there is input */
len = elimws(line, len);
reverse(line, len);
for (i = 0; i < MAXLINE - len; ++i)
putchar(' ');
printf("%s\n", line);
}
return 0;
}
/* elimws: eliminates trailing whitespace from input array 's' of
length 'lim' and returns length of newly reduced array */
elimws(s, lim)
char s[];
int lim;
{
while (lim > 0 && (s[lim-1]=='\n' || s[lim-1]=='\t' || s[lim-1]==' ')) {
s[lim-1] = '\0';
--lim;
}
return lim;
}
/* reverse: reverses the character string 's' */
reverse(s, lim)
char s[];
int lim;
{
int i;
char s2[MAXLINE]; /* temp array to hold reversed string */
for (i = 0; i < lim; ++i)
s2[i] = s[lim-1-i];
s2[lim] = '\0';
copy(s, s2);
return 0;
}
/* getline: read a line into s, returns length */
getline(s, lim)
char s[];
int lim;
{
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
copy(to, from)
char to[], from[];
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
return 0;
}