简体   繁体   中英

C- K&R exercise 1-9

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.

lch正在获取旧字符,因此ch正在获取getchar() ,运行循环,当完成时,该值由lch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM