1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    It might be helpful if you posted your variant that doesn't work as you expect. "the third condition of for loop and if statement" is quite a bit harder to parse than C. – mevets Mar 13 '20 at 20:19
  • 4
    This is an example of why clear variable names are important. If `lch` would have been named `last_char`, would you have had to ask the question? – Fred Larson Mar 13 '20 at 20:20

2 Answers2

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

lch is getting the old character, so the ch is getting getchar(), run the loop, and when this is finished, the value is taken by lch.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278