Why Should We Track The Inside Of The Word In K&R Exercise 1-11?
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.
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.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page