Ad

Why Should We Track The Inside Of The Word In K&R Exercise 1-11?

- 1 answer

Here is the exercise:

Write a program that prints its input one word per line.

My solution to this exercise is the following:

main() {
    int c; 
    while((c = getchar()) != EOF) { 
        if(c == ' ' || c == '\t' ) 
            putchar('\n');
        else
            putchar(c);
        }
    }
}

According to this link it is a bad solution, but I'm not sure I understand why.

I would appreciate some help understanding this.

Ad

Answer

The problem is when your input contains more than one newline, tab or space in subsequent order.

Then it always jumps into a new line, although it shouldn't.

The requirement of to "print one word per line" is not fulfilled then.

You need to keep an eye on whether the newline, tab or space occurs after a sequence of non-instruction characters or not. So we need a "STATE" parameter which documents the current state.

Chrismath's solution covers that:

// print input one word per line 

#define IN 1 
#define OUT 0 

int main (void) 
{ 
      int c, state; 
      // start without a word 
      state = OUT; 
         
      while ((c = getchar()) != EOF) { 
              // if the char is not blank, tab, newline 
              if (c != ' ' && c != '\t' && c != '\n') { 
                      // inside a word 
                      state = IN; 
                      putchar(c); 
              // otherwise char is blank, tab, newline, word ended 
              } 
              else if (state == IN) { 
                      state = OUT; 
                      putchar('\n'); 
              } 
      } 
      return 0;
}

The newline is only printed when state is IN which means at least a word of one character was printed in a line before it get to another one.

Someone could argue that a word wouldn't be a single character, but then we would need an explicit requirement of how many characters at least a word is consisted of, but this isn't provided to the task here, so the one character word is plausible and legit.

Ad
source: stackoverflow.com
Ad