Search code examples
cgetchar

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 !


Solution

  • The program doesn't need multiple loops statements or any else statements.

    This seems like a straight-forward way to solve the problem:

    #include <stdio.h>
    int main(void) {
        int single_byte;
        int last_char;
        for(last_char = 0; (single_byte = getchar()) != EOF; last_char = single_byte)
        {
            if(last_char != ' ' || single_byte != ' ')
                putchar(single_byte);
        }
    }