looking for exercise 1-9 from the K&R book (Copy input to output. Replace each string of multiple spaces with one single space) I found this code on this site.
#include <stdio.h>
main()
{
int ch, lch;
for(lch = 0; (ch = getchar()) != EOF; lch = ch)
{
if (ch == ' ' && lch == ' ')
;
else
putchar(ch);
}
}
The program works, but the operation is not clear to me: what is the variable lch for? Why not inserting it inside the third condition of for loop and if statement the program does not give the correct output?
You need to substitute several spaces with one space. So if the previous inputted character was space and the current inputted character is also space when you need to skip the current character.
So lch stores the value of the previous inputted character. Initially when there was not yet any input lch is set to 0. Then in each iteration lch is set to the current inputted character that in this if statement
if (ch == ' ' && lch == ' ')
whether the current character and the previous character are both spaces. If so then the program outputs nothing.