Desmond Nutes
Desmond Nutes

Reputation: 103

I don't understand the difference in this code sample for K&R exercise 1-12

Im trying to figure out K&R exercise 1-12 and stumbled across this answer:

#include <stdio.h>

#define IN  1
#define OUT 0

main()
{

int c, state;

state = OUT;

while ((c = getchar()) != EOF) {
    if (c != ' ' && c != '\n' && c != '\t') {
        state = IN;
        putchar(c);
    }
    else
        if (state == IN) {
            state = OUT;
            putchar('\n');
        }
}

if (state == IN)
    putchar('\n');
}

Whats the purpose of

 if (state == IN)
    putchar('\n');

if i take this out of the code it still runs the exact same. Could some please explain to me the purpose of putting that extra if statement into the code.

Also is there any simpler way to write this code without using things ahead of the books chapter?

Upvotes: 0

Views: 79

Answers (1)

Arkku
Arkku

Reputation: 42149

If the end state is OUT, as it usually is, then there is no difference. If the end state is IN (i.e., input does not have trailing whitespace, such as newline) this terminates the last line of output with a newline.

Upvotes: 4

Related Questions