:: [DNG] [OT] [Re: Studying C as told…
トップ ページ
このメッセージを削除
このメッセージに返信
著者: KatolaZ
日付:  
To: dng
古いトピック: [DNG] Studying C as told. (For help)
題目: [DNG] [OT] [Re: Studying C as told. (For help)
On Mon, Jun 20, 2016 at 04:37:08PM +0200, Edward Bartolo wrote:

[cut]

>
> 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?
>
> --------------------------
> #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;
> }
> ----------------------------



It looks plain and correct to me :) An equivalent version which avoids
the chain of ifs might read:

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

int main (int argc, char *argv[]){

  int c,d=0;
    while((c=getchar()) != EOF){
        putchar(c);
    while(c == ' ' && (c=getchar()) != EOF ){
        d=1;
        }
    if (d){
            putchar(c);
    }
    d=0;
    }
}


-----

which can be further streched into:

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

int main (int argc, char *argv[]){

    int c,d=0;
    while((c=getchar()) != EOF){
        c=putchar(c);
    while(c == ' ' && (c=getchar()) != EOF && (d=1));
    if (d && putchar(c) && (d=0));
    }
}



-----

But, admittedly, sacrifying quite a lot in terms of readability
without a reason.

WD

KatolaZ

-- 
[ ~.,_  Enzo Nicosia aka KatolaZ - GLUGCT -- Freaknet Medialab  ]  
[     "+.  katolaz [at] freaknet.org --- katolaz [at] yahoo.it  ]
[       @)   http://kalos.mine.nu ---  Devuan GNU + Linux User  ]
[     @@)  http://maths.qmul.ac.uk/~vnicosia --  GPG: 0B5F062F  ] 
[ (@@@)  Twitter: @KatolaZ - skype: katolaz -- github: KatolaZ  ]