该程序是 K&R 书籍《C 编程语言》中的练习:
编写一个程序,将其输入复制到输出,用一个空格替换每个包含一个或多个空格的字符串。
#include<stdio.h>
#define NONBLANK 'a'
int main(void)
{
int c, lastc;
lastc = NONBLANK;
while ((c = getchar()) != EOF){
if ( c != ' ')
putchar(c);
if ( c == ' ')
if (lastc != ' ')
putchar(c);
lastc = c;
}
}
}
我只是想知道这个程序如何在无聊的细节中运作。
最佳答案
嗯。锻炼 ?无聊的细节?
#include<stdio.h>
#define NONBLANK 'a' /* a fake char to use later */
main()
{
int c, lastc;
lastc = NONBLANK; /* now last c == char 'a' */
while ((c = getchar()) != EOF){ /* parse input (stdin), char by char */
if ( c != ' ') /* if the char is a *not* a space ..*/
putchar(c); /* then write it on stdout; */
if ( c == ' ') /* if it is a space ..*/
if (lastc != ' ') /*.. and lastc is *not* a space ..*/
putchar(c); /* then write it on stdout; */
lastc = c; /* Make lastc be equal to the current */
/* parsed char, and loop up to while */
}
}
PS:第一次在这里..抱歉格式困惑。
HTH
-- 米歇尔·马尔孔(又名 cmic)
关于c - 了解 K&R 中的练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20588913/