Friday, 27 September 2013

About the EX1-9 of K&R

About the EX1-9 of K&R

Here's the text of Exercise 1-9 from the book 'The C programming language'
by Ritchie&Kernighan:
Write a program to copy its input to its output, replacing each string of
one or more blanks by a single blank.
To me the simplest way of solving that problem is writing
int single_byte = getchar();
while (single_byte != EOF) {
putchar(single_byte);
if (single_byte == ' ')
while ((single_byte = getchar()) == ' ')
;
else
single_byte = getchar();
}
though I was told (last night in the #c channel of irc.freenode.net) it
would be more readable getting rid of the nested while by implementing a
comparison between the last character saved and the one just read. What I
thought is kind of this:
int current_byte = getchar();
if (current_byte == EOF)
return 1;
putchar(current_byte);
int previous_byte = current_byte;
while ((current_byte = getchar()) != EOF) {
if (current_byte == ' ' && previous_byte == ' ')
;
else
putchar(current_byte);
previous_byte = current_byte;
}
that does not satisfy me at all: starting from the first if-statement (for
the case when there's nothing to read). Additionally I wish I could push
the last two lines before the while inside the loop; the less I should
distinguish the beginning from the rest of the execution, the happier I am
!

No comments:

Post a Comment