:: Re: [DNG] Studying C as told. (For …
Góra strony
Delete this message
Reply to this message
Autor: Irrwahn
Data:  
Dla: dng
Temat: Re: [DNG] Studying C as told. (For help)
On Mon, 20 Jun 2016 16:37:08 +0200, Edward Bartolo wrote:
[...]
> "The C programming language" (Kernighan & Ritchie)

[...]
> 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;
> }
> ----------------------------


Good job so far! Note to other readers: The 'else' keyword has
not been covered at this point in the book. So the solution
looks a bit suboptimal, but is correct nonetheless.

However, since the '&&' operator has not been covered as well,
the second if-block would read something like that in a
straight-forward true-to-the-letter solution:

     if (c == ' ') { 
       if (d == 0) {
         putchar(c);
         d = 1;
       }
     }


One more hint: There exists a web page listing possible solutions
to the exercises in K&R2, peer reviewed by designated expert C
programmers:

http://clc-wiki.net/wiki/K%26R2_solutions

HTH, Regards
Urban