:: Re: [DNG] Studying C as told. (For …
Top Pagina
Delete this message
Reply to this message
Auteur: Edward Bartolo
Datum:  
Aan: Peter Olson
CC: dng
Onderwerp: Re: [DNG] Studying C as told. (For help)
Hi,

I am saving your program for future study as its level is beyond the
current level I am at. I am still at page 34 ("The C programming
language" (Kernighan & Ritchie))

Thanks, Edward

On 21/06/2016, Peter Olson <peabo@???> wrote:
>> On June 20, 2016 at 10:37 AM Edward Bartolo <edbarx@???> 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
>