Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site ucla-cs.ARPA Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!decvax!ittatc!dcdwest!sdcsvax!sdcrdcf!ucla-cs!jimc From: jimc@ucla-cs.UUCP Newsgroups: net.lang Subject: Re: Comments on this program please... Message-ID: <7839@ucla-cs.ARPA> Date: Mon, 2-Dec-85 19:04:18 EST Article-I.D.: ucla-cs.7839 Posted: Mon Dec 2 19:04:18 1985 Date-Received: Thu, 5-Dec-85 06:47:52 EST References: <2389@ukma.UUCP> Reply-To: jimc@ucla-cs.UUCP (Jim Carter) Organization: UCLA Computer Science Department Lines: 65 In article <2389@ukma.UUCP> david@ukma.UUCP (David Herron, NPR Lover) writes: >Everybody I've shown this program to has *groaned* ... >I think it's *cute*! >#include >main() >{ > register int r, o, u, t, e; > while ((r = getchar()) != EOF) { > if (r == 'R') > if ((o = getchar()) == 'O') > if ((u = getchar()) == 'U') > if ((t = getchar()) == 'T') > if ((e = getchar()) == 'E') > printf("\nROUTE"); > else > printf("ROUT%c", e); > else > printf("ROU%c", t); > else > printf("RO%c", u); > else > printf("R%c", o); > else > putchar(r); > } > putchar('\n'); >} Yes, indeed, the above program is aesthetically disgusting. But what is wrong with it in practice? 1. It works only for that one pattern (not that files are often wiped like that, but let's keep our standards up). 2. The multiple if's and library calls can get lengthy on some mach- ines. 3. Using printf is expensive when you just want to concatenate strings on the way out. Here is a looping version. Isn't this one just as cute? #include main(an, av) int an; char *av[]; /*When the pattern av[1] is found in stdin, a new- *line is put in front of it, the result going to *stdout. */ { register char c, *p, *r; if (an < 2) {puts("Usage: gorf pattern"); exit(1);} /*Idiotproof*/ for (p = av[1]; ; ) { c = getchar(); if (c == *p && c != '\0') { /*Char does match pattern (last term is *nitpick overkill since \0 unlikely in text). *Note, EOF doesn't match pattern.*/ if (*++p == '\0') putchar('\n'); /*Found whole pattern, write new- *line before it. Pattern dumped on next char.*/ } else { /*Char. doesn't match pattern*/ for (r = av[1]; r < p; ) putchar(*r++); /*Dump portion of pattern, *if any, that was matched*/ if (c == EOF) break; putchar(c); /*After which, write non-matching char.*/ p = av[1]; /*Again start looking for pattern*/ } } } (Bug: if the pattern is ROUTE and the text is ROUROUTE, the pattern will be missed. This is an easy fix. But if the pattern is TINTINABULATION and the text is TINTINTINABULATION, even with the above fix the pattern will be missed. It could be seen only with long and expensive pattern checking -- or does someone see a smart way to do it?