Exercise 1-9. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
这是课文中复制-输出程序例子的一个变形,作者要求我们做一点点变形,将复制过程中遇到的单个空格或者连续多个空格都只用一个空格来输出代替。
这次我们首先贴出完整代码:
#include <stdio.h>
#define NEW_BLANK 1
#define NOT_NEW_BLANK 0
int main(void) {
int c, cState;
cState = NEW_BLANK;
while((c = getchar()) != EOF) {
if (c != ' ') {
putchar(c);
cState = NEW_BLANK;
}
else {
if (cState == NEW_BLANK) {
putchar(c);
cState = NOT_NEW_BLANK;
}
}
}
return 0;
}
接着我们分析一下。
首先我们定义了两个宏,用来表示是否遇到了新的空格(串):
#define NEW_BLANK 1 //表示进入了一个新的空格(串)
#define NOT_NEW_BLANK 0 //表示在一个空格(串)之