Specifically, the code is a solution to Exercise 1-9 in K&R C Programming Language 2nd Edition. I already solved it, but I have a question.
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
This code works and returns the desired output
int ch, last;
for (last = 0; (ch = getchar()) != EOF; last = ch)
if (ch == ' ' && last == ' ')
;
else
putchar(ch);
This version of the code doesn't work and instead prints literally the same input with excess spaces included.
int ch, last;
last = 0;
while ((ch = getchar()) != EOF)
if (ch == ' ' && last == ' ')
;
else
putchar(ch);
last = ch;
Could somebody tell me the difference between these two versions of code and why the latter version doesn't work?
In the 2nd version you need to place the body of the while loop in a {} as it consist of two statements (if
and last=
assignment). Otherwise only the first statement is executed in the loop, and the 2nd after the loop terminates.
int ch, last;
last = 0;
while ((ch = getchar()) != EOF) {
if (ch == ' ' && last == ' ')
;
else
putchar(ch);
last = ch;
}
I would invert the condition:
if (ch != ' ' || last != ' ')
putchar(ch);