:: Re: [DNG] (no subject)
Página Principal
Delete this message
Reply to this message
Autor: Rainer Weikusat
Data:  
Para: dng
Assunto: Re: [DNG] (no subject)
Edward Bartolo <edbarx@???> writes:

[...]

> 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 seems to work, but I think it is
> too complicated. Any suggestions?
>
> --------------------------
> #include <stdio.h>
>
> int main()
> {
>   int c, d = 0;
>   while ((c = getchar()) != EOF) {
>     if (c != ' ') {
>       d = 0;
>       putchar(c);
>     }
>     if (c == ' ' && d == 0) {
>       putchar(c);
>       d = 1;
>     }
>   }

>
> return 0;
> }
> ----------------------------


Conventional approach using a state variable:

--------
#include <stdio.h>

int main(void)
{
    int c, blanks;


    blanks = 0;
    while ((c = getchar()) != EOF) {
    if (blanks) {
        if (c == ' ') continue;
        blanks = 0;
    } else
        blanks = c == ' ';


    putchar(c);
    }


    return 0;
}
--------


Less conventional approach using a function pointer as state variable.

NB: This is really overkill here but very helpful in case of (much) more
complicated state machines.

--------
#include <stdio.h>

static void put_a_char(int);

static void (*process_char)(int) = put_a_char;

static void skip_blanks(int c)
{
    if (c == ' ') return;


    process_char = put_a_char;
    putchar(c);
}


static void put_a_char(int c)
{
    putchar(c);
    if (c == ' ') process_char = skip_blanks;
}



int main(void)
{
    int c;


    while ((c = getchar()) != EOF) process_char(c);


    return 0;
}
--------