The while
loop continues to execute as long as it gets a character from stdin
that is not EOF
:
while((c = getchar()) != EOF)
Two char
variables are declared: c
and lastc
. For this logic to work, the current character and the previous character must be known. Initially, lastc
does not have a value, but it’s used nonetheless:
if(lastc != ' ')
putchar(c);
It is possible that when the program starts lastc
will have a garbage value that != ' '
. It would be a very good idea to define this variable when you declare it to a sane value:
int c, lastc=" ";
The logic is as follows:
The current character is read from stdin
. If it is not the space character (' '
), it is written to stdout
. If it is a space, the space is written to stdout
only if the previous character was not a space. If the previous character was a space, the current space is ignored as to make only one space printed if there is a series of space characters in stdin
.
solved Understanding an exercise in K&R [closed]