> On June 20, 2016 at 10:37 AM Edward Bartolo <edb...@gmail.com> wrote: > > On page Page 34 Exercise 1-9 > "Write a program to copy its input to its output, replacing each > string of blanks one ore more blanks by a single blank." > > I wrote the following, tested it, and it seems to work, but I think it is > too complicated. Any suggestions?
Here's another way to do it: /* * K&R exercise * * Replace multiple blanks with single blank */ #include <stdio.h> #include <string.h> #include <errno.h> static int filter (void) { int ch = getchar (); /* all the logic is here */ if (EOF != ch) { putchar (ch); if (' ' == ch) for (;;) { ch = getchar (); if (' ' != ch) { if (EOF != ch) putchar (ch); break; } } } return ch; } static int checkError (FILE * fp, const char *arg) { if (ferror (fp)) { const char *pgmName = strrchr (arg, '/'); if (pgmName) pgmName++; /* get beyond the slash */ else pgmName = arg; fprintf (stderr, "%s: I/O error: %s\n", pgmName, strerror (errno)); return 1; } return 0; } int main (int argc, char **argv) { while (EOF != filter ()) continue; /* this version encodes state in program structure */ if (checkError (stdin, argv[0])) return 1; /* this version checks for errors */ if (checkError (stdout, argv[0])) return 1; /* I didn't actually reproduce this error, it is hard to test */ return 0; } I hope this survives line wrapping :-) Peter Olson _______________________________________________ Dng mailing list Dng@lists.dyne.org https://mailinglists.dyne.org/cgi-bin/mailman/listinfo/dng